2014-10-19 32 views
0

我一直在玩一個應用程序,當按下按鈕時會顯示一個隨機的笑話。從字典/數組中選擇一個隨機字符串在按下按鈕時顯示在UILabel中

我已經宣佈了兩個插座(一個用於按鈕,一個用於顯示笑話的標籤)。當按下「jokeButton」時,我已成功獲取代碼以顯示一行文本。雖然,我怎樣才能輸入一大羣笑話,然後按下笑話按鈕時隨機顯示一個笑話。

我曾嘗試搞亂NSArray和NSDictionary,並做了一些谷歌搜索,但沒有成功。

@implementation ViewController 

- (void)viewDidLoad { 

[super viewDidLoad]; 

self->jokeLabel.text = (@"Welcome to The Joke Panel!"); 
} 

- (IBAction)jokeWasPressed:(id)sender { 
NSLog(@"Joke Button Was Pressed"); 
self->jokeLabel.text = (@"Why did the chicken cross the road? -- To get to the other side!"); 
} 

非常感謝您的幫助! PS抱歉,我剛開始學習!

+0

如果你想有一個大笑話基地,你可能要考慮使用的核心數據。即使你沒有,也可能值得研究它,因爲它是iOS值得學習的非常有用的一部分。然而,對於少於500個條目,數組足夠好。 – 2014-10-19 21:10:50

回答

0

您正在創建一個字符串數組的正確軌道。下一步將生成一個隨機數並將其用作索引值以從數組中獲取字符串。

查詢arc4random瞭解有關創建隨機數字的信息。

0
//Declare "NSMutableArray *arrJokes;" globally 

//Initialize array to hold strings which will essentially be the Jokes 
arrJokes = [[NSMutableArray alloc] init]; 

//Add jokes 
[arrJokes addObject:@"Joke 1"]; 
[arrJokes addObject:@"Joke 2"]; 
[arrJokes addObject:@"Joke ..."]; 
[arrJokes addObject:@"Joke N"]; 

//generate a random index between 0 and arrJokes.count 
int randomIndex = arc4random()%arrJokes.count; 

//pick the string that is at this randomIndex in arrJokes and set it on the label 
[jokeLabel setText:arrJokes[randomIndex]]; 
+0

'arrJokes'不像書面那樣可變。 – rmaddy 2014-10-19 21:16:39

+0

@rmaddy:哎呀,是的。 \*嘆\* – staticVoidMan 2014-10-19 21:18:02

相關問題