2011-02-03 57 views
1

我想創建一個數組,其中包含x數量的字面字符串,它會在您點擊一個UIButton後隨機發送一個到UILabel。發送到UILabel的隨機文本

我應該如何構造.h和.m文件來完成此操作?另外,生成我需要的隨機數的最佳方法是什麼?

+0

您還沒有提問。 – 2011-02-03 17:53:08

+4

他顯然在問如何做到上述。常識。 – 2011-02-03 18:13:30

回答

1

你會得到該指數的隨機整數,然後只是通過你到UILabel的文本屬性的對象,如:

//assuming you already have an NSArray of strings 
myLabel.text = [arrayOfString objectAtIndex:arc4random() % [arrayOfString count]]; 

你最好把上面的代碼中的方法按鈕當它被按下時調用。編輯:As requested here's a simple Xcode project。 (注意:因爲它是隨機的,所以你可能會得到相同的文本,所以它可能看起來文本不會改變,它會改變,但它會改變爲與之前沒有看到的文本相同的文本)

+0

謝謝你們,我對邏輯有一個相當好的想法,但是我很難在.h,.m和正確放置IB元素中使用正確的語法。 如果不是太多,有人可以發佈一個非常簡單的/通用的Xcode項目,這樣我就可以剖析它了嗎? 謝謝哦,非常非常。 非常好奇/有野心的新手。 – 2011-02-05 20:08:21

0
- (void) applicationDidFinishLaunching:(UIApplication*)application 
{ 
    //Create window 
    _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
    [_window makeKeyAndVisible]; 
    sampleArray = [[NSArray arrayWithObjects: @"iPhone", @"iPod", @"iMac", @"Newton",@"iPad",@"Lisa",@"Mac mini",@"Delta" ,nil] retain]; 
    randButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain]; 
    [randButton setFrame:CGRectMake(20.0f, 30.0f, 60.0f, 40.0f)]; 
    [randButton setTitle:@"Random" forState:UIControlStateNormal]; 
    [randButton addTarget:self action:@selector(randNumberGenerate) forControlEvents:UIControlEventTouchUpInside]; 
    [_window addSubview:randButton];  
} 


- (void) randNumberGenerate 
{ 
    NSString* string = [sampleArray objectAtIndex:(arc4random()%[sampleArray count])]; 
    UILabel* displayRandNum = [[UILabel alloc] initWithFrame:CGRectMake(120.0f, 30.0f, 80.0f, 30.0f)]; 
    displayRandNum.text = string; 
    [_window addSubview:displayRandNum]; 
    [displayRandNum release]; 
}