我想要一個UIButton
,它將更改系列中標籤的文本。例如,我可能有一個標籤,上面寫着hello
。如何使用UIButton多次更改標籤?
然後當我按下一個按鈕時,它將更改爲,What's up?
。
但是第二次點擊同一個按鈕會將標籤更改爲Nuttin' much!
。
我知道如何將標籤的文字更改一次,但是如何使用相同的按鈕多次更改它?優選地,大約20到30個單獨的文本。
預先感謝您! :D
我想要一個UIButton
,它將更改系列中標籤的文本。例如,我可能有一個標籤,上面寫着hello
。如何使用UIButton多次更改標籤?
然後當我按下一個按鈕時,它將更改爲,What's up?
。
但是第二次點擊同一個按鈕會將標籤更改爲Nuttin' much!
。
我知道如何將標籤的文字更改一次,但是如何使用相同的按鈕多次更改它?優選地,大約20到30個單獨的文本。
預先感謝您! :D
這非常開放。考慮將屬性添加到您的類中,這是一個字符串數組的索引。每次按下按鈕時,都會增加數組(數組的模數大小)並使用相應的字符串更新按鈕。但有很多其他方法可以做到這一點...
在viewDidLoad方法中,創建一個包含字符串的數組來保存標籤。然後創建一個變量來跟蹤哪個對象應該被設置爲當前標籤。設置初始文本:
NSArray *labelNames = [[NSArray alloc] initWithObjects:@"hello",@"what's up?", @"nuttin much"];
int currentLabelIndex = 0;
[label setText:[labelNames objectAtIndex:currentLabelIndex]];
然後在輕按按鈕時調用的方法中,更新文本和索引。
- (IBAction) updateButton:(id)sender {
// this finds the remainder of the division between currentLabelIndex+1 and labelNames.count. If it is less than the count, its just the index. If its equal to the count we go back to the beginning of the array.
currentLabelIndex = (currentLabelIndex+1)%labelNames.count;
[label setText:[labelNames objectAtIndex:currentLabelIndex]];
}
我在哪裏把: 「int currentLabelIndex = 0;」和「,[button setTitle:[labelNames objectAtIndex:currentLabelIndex] forState:UIControlStateNormal];」在我的代碼? –
@bkbeachlabs,你正在設置按鈕的標題,而不是標籤的文本屬性,這是問題。 – Computerspezl
@MickBraun哎呀,你是對的!抱歉!更新和修復。 – bkbeachlabs
當應用程序用完短語時會發生什麼?重來?典型的方法看起來像這樣。
@property (strong, nonatomic) NSArray *phrases;
@property (assign, nonatomic) NSInteger index;
- (IBAction)pressedButton:(id)sender {
// consider doing this initialization somewhere else, like in init
if (!self.phrases) {
self.index = 0;
self.phrases = @{ @"hello", @"nuttin' much" }; // and so on
}
self.label.text = self.phrases[self.index];
self.index = (self.index == self.phrases.count-1)? 0 : self.index+1;
}
我害怕我只是一個初學者..怎麼會有人去編碼呢? –
@BrandonBoynton,有人可能總是爲積分提供實際的代碼,或者因爲他們感覺很有學術性,但是當你提出一般問題時,你應該期待一般的答案。 StackOverflow通常不是程序員免費編寫代碼的地方。 +1提供「保存狀態」答案。 –
我很抱歉,但我認爲這超出了本網站的預期範圍。閱讀文檔或找到關於NSArray的教程,這應該讓你開始。我非常喜歡Ray Wenderlich發佈的網站。你會發現在這裏:http://www.raywenderlich.com/tutorials – KHansenSF