我如何在objective-c中编辑所有带有特定标签的uibutton



我想编辑所有带有特定标签的按钮。我从0-15标记了每个ui按钮(我在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];
    }
}

我在谷歌上找遍了,什么也找不到。谢谢。

感谢inspirre48和Alex Nichol,我设法想出了一个答案。如果您尝试从i = 0开始,代码会抛出一个错误:'NSInvalidArgumentException', reason: '-[UIView setTitle:forState:]: unrecognized selector sent to instance 0xa180970。因此,为了弥补这一点,我只是在我的pList中添加了一个索引0处的空白条目,这允许我在i = 1而不是i = 0处开始我的for()语句。

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

我必须对inspirre48和Alex Nichol使用的代码进行的另一个更改如下。代替[self viewWithTag:i],你需要使用[self.view viewWithTag:i]

再次感谢大家!

使用标准的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];
}

Inspire48上面的代码几乎是正确的,只有一个小错误。您希望遍历从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];

最新更新