简体   繁体   English

如何使用UIButton多次更改标签?

[英]How do I use a UIButton to change a label multiple times?

I want to have one UIButton that will change the text of a label in a series. 我想要一个UIButton ,它将更改一系列标签的文本。 For example, I may have a label that says hello . 例如,我可能有一个标签“ hello

Then when i push a button, it will change to, What's up? 然后,当我按一个按钮时,它将变为: What's up? .

But then a second tap of the same button will change the label to Nuttin' much! 但是,再次点击同一按钮将把标签更改为Nuttin' much! .

I know how to make the text of a label change once, but how do I change it many times with the same button? 我知道如何使标签的文本更改一次,但是如何使用同一按钮将其更改多次? Preferably, anywhere around 20 to 30 separate texts. 最好在20到30个单独的文本附近。

Thank you in advance! 先感谢您! :D :D

That's pretty open ended. 这很开放。 Consider adding a property to your class which is an index into an array of strings. 考虑将一个属性添加到您的类中,该属性是字符串数组的索引。 Each time you push the button increment the array (modulo size of array) and use the corresponding string to update the button. 每次按下按钮时,将增加数组(数组的模数),并使用相应的字符串更新按钮。 But there are a lot of other ways you could do this... 但是您还有很多其他方法可以执行此操作...

What happens when the app runs out of phrases? 当应用程序用完短语时会发生什么? Start over? 重来? The typical approach would look like this. 典型的方法如下所示。

@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;
}

In the viewDidLoad method, create an array with strings to hold the labels. 在viewDidLoad方法中,创建一个带有字符串的数组以保存标签。 Then create a variable to keep track of which object should be set as the current label. 然后创建一个变量,以跟踪应将哪个对象设置为当前标签。 Set the initial text: 设置初始文本:

NSArray *labelNames = [[NSArray alloc] initWithObjects:@"hello",@"what's up?", @"nuttin much"];
int currentLabelIndex = 0;
[label setText:[labelNames objectAtIndex:currentLabelIndex]];

Then in the method that gets called when the button is tapped, update the text and the index. 然后,在点击按钮时调用的方法中,更新文本和索引。

- (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]];

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM