我想用特定标签编辑所有按钮。我已经从0到15标记了每个UIButton(我在IB中构建)。然后我在我的NSMutableArray(investigationsArray)中搜索时使用标记按钮作为索引值。我的阵列中有16个项目。
我想在viewWillAppear中实现类似的东西:
if (theButtonTag == 0){
[button setTitle: [[investigationsArray objectAtIndex:0]objectForKey:@"name"] forState:UIControlStateNormal];
}
我想简化我的代码,所以最终我可以使用这样的for语句:
for (buttonTag = 0; buttonTag < [investigationsArray count]; buttonTag ++){
if (theButtonTag == i){
[button setTitle: [[investigationsArray objectAtIndex:i]objectForKey:@"name"] forState:UIControlStateNormal];
}
}
我看了一遍谷歌,找不到任何东西。谢谢你们。
答案 0 :(得分:4)
感谢Inspire48和Alex Nichol,我设法得到了答案。如果您尝试从i = 0
开始,则代码会引发错误:'NSInvalidArgumentException', reason: '-[UIView setTitle:forState:]: unrecognized selector sent to instance 0xa180970
。所以为了弥补这一点,我在index0中添加了一个空白条目到我的pList中,这样我就可以在for()
而不是i = 1
开始我的i = 0
语句。
for (int i = 1; i < [investigationsArray count]; i++) {
UIButton * button = (UIButton *)[self.view viewWithTag:i];
NSString * title = [[investigationsArray objectAtIndex:i] objectForKey:@"name"];
[button setTitle:title forState:UIControlStateNormal];
}
我必须对Inspire48和Alex Nichol使用的代码进行的另一项更改如下。您需要使用[self viewWithTag:i]
。
[self.view viewWithTag:i]
再次感谢你们!
答案 1 :(得分:0)
使用标准for
循环,就像你在那里一样。 UIView
有一个名为viewWithTag的方法,它将返回带有指定标记的视图。这正是你想要的。
代码段:
for (int i = 0; i <= 15; i++) {
UIButton *button = (UIButton *)[self viewWithTag:i];
[button setTitle: [[investigationsArray objectAtIndex:0]objectForKey:@"name"] forState:UIControlStateNormal];
}
答案 2 :(得分:0)
上面的Inspire48代码几乎是正确的,有一个小bug。您希望遍历0到15之间的所有标记,并将该按钮的标题设置为数组中的值。以下是一些示例代码:
for (int i = 0; i < [investigationsArray count]; i++) {
UIButton * button = (UIButton *)[self viewWithTag:i];
NSString * title = [[investigationsArray objectAtIndex:i] objectForKey:@"name"];
[button setTitle:title forState:UIControlStateNormal];
}
我建议最后不使用按钮标签,而是将按钮作为NSDictionary中的按键。然后你可以有类似的东西:
for (UIView * view in [self subviews]) {
if ([view isKindOfClass:[UIButton class]) {
UIButton * button = (UIButton *)view;
NSString * title = [[investigationsDictionary objectForKey:button] objectForKey:@"name"];
[button setTitle:title forState:UIControlStateNormal];
}
}
您可以按如下方式初始化词典:
NSDictionary * investigationsDictionary;
...
investigationsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:button1, myValue,...,nil];