我想要一个UIButton
可以更改系列中标签文本的产品。例如,我可能有一个标签,上面写着hello
.
然后当我按下一个按钮时,它会变成,What's up?
。
但随后再次点击同一按钮会将标签更改为Nuttin' much!
。
我知道如何使标签的文本更改一次,但是如何使用同一个按钮多次更改它?最好是大约 20 到 30 个单独的文本。
先感谢您!:D
这是相当开放的结局。考虑向您的类添加一个属性,该属性是字符串数组的索引。每次按下按钮都会增加数组(数组的模大小)并使用相应的字符串来更新按钮。但是还有很多其他方法可以做到这一点......
当应用程序用完短语时会发生什么?重来?典型的方法如下所示。
@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;
}
在 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]];
}