Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/93.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何使用UIButton多次更改标签?_Ios_Uibutton - Fatal编程技术网

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

Ios 如何使用UIButton多次更改标签?,ios,uibutton,Ios,Uibutton,我想有一个UIButton,它可以改变一系列标签的文本。例如,我可能有一个标签,说你好 然后当我按下一个按钮时,它会变成,怎么了 但是,第二次点击同一个按钮会将标签更改为Nuttin'more 我知道如何使标签的文本更改一次,但如何使用同一按钮更改多次?最好是20到30个左右的单独文本 提前谢谢你!:这是非常开放的。考虑将属性添加到类中,该属性是字符串数组的索引。每次按下按钮时,都会增加数组的数组模大小,并使用相应的字符串更新按钮。但是还有很多其他方法可以做到这一点…在viewDidLoad方法

我想有一个UIButton,它可以改变一系列标签的文本。例如,我可能有一个标签,说你好

然后当我按下一个按钮时,它会变成,怎么了

但是,第二次点击同一个按钮会将标签更改为Nuttin'more

我知道如何使标签的文本更改一次,但如何使用同一按钮更改多次?最好是20到30个左右的单独文本


提前谢谢你!:这是非常开放的。考虑将属性添加到类中,该属性是字符串数组的索引。每次按下按钮时,都会增加数组的数组模大小,并使用相应的字符串更新按钮。但是还有很多其他方法可以做到这一点…

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

}

当应用程序的词组用完时会发生什么?重新开始?典型的方法是这样的

@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通常不是程序员免费编写代码的地方+我很抱歉,但我认为这超出了本网站的预期范围。阅读文档或查找有关NSArray的教程,这应该会让您开始学习。我真的很喜欢Ray Wenderlich发布的网站。你会发现:我把:int currentLabelIndex=0放在哪里;以及[button setTitle:[labelNames objectAtIndex:currentLabelIndex]for状态:UIControlStateNormal];在我的代码?@bkbeachlabs中,您设置的是按钮的标题,而不是标签的文本属性,这是问题所在。@BrandonBoynton这些行在您的viewDidLoad中。