迭代sender.superview

时间:2015-07-20 15:20:21

标签: ios objective-c

我在视图中放置了6个按钮并尝试相应地更改背景颜色:

- (IBAction)btnPressed:(UIButton *)sender {
    for(UIButton *btn in sender.superview){
        [btn setBackgroundColor:[UIColor whiteColor]];
    }
    [sender setBackgroundColor:[UIColor blackColor]];
}

以下错误消息: [UIView countByEnumeratingWithState:objects:count:]:无法识别的选择器发送到实例0x174191d30 2015-07-20 17:12:00.853 Raymio [20370:2209236] ***由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' - [UIView countByEnumeratingWithState:objects:count:]:无法识别的选择器发送到实例0x174191d30'

我确实得到了一个编译器警告警告可能会发生这种情况,但是我不能正确地获取发件人的超级视图吗?

编辑:也许我误会了......我有一个视图控制器(主视图obv)。在那个vc中我有很多视图,包括我有6个按钮的视图。我想只获得该特定视图中的6个按钮,因此我试图获得发送者的超级视图,以为我得到了用于放置6个按钮的视图。

2 个答案:

答案 0 :(得分:1)

要枚举子视图,请确保您引用子视图数组:

for (UIButton *btn in sender.superview.subviews) {

    if ([btn isKindOfClass:[UIButton class]]) {
        [btn setBackgroundColor:[UIColor whiteColor]];
    }
}

答案 1 :(得分:0)

sender.superview不符合NSFastEnumeration protocol。您可能希望遍历sender.subviews(或sender.superview.subviews),如:

- (IBAction)btnPressed:(UIButton *)sender {
  for(UIButton *btn in sender.subviews){
    [btn setBackgroundColor:[UIColor whiteColor]];
  }
  [sender setBackgroundColor:[UIColor blackColor]];
}

编辑:

正如我所说,您可以使用按钮定义插座集合:

@property(nonatomic, strong) IBOutletCollection(UIButton) NSArray *buttons;

创建这些按钮,将它们添加到此数组中(或通过Interface Builder连接)并执行下一步:

- (IBAction)btnPressed:(UIButton *)sender {
  for(UIButton *btn in buttons){
     [btn setBackgroundColor:[UIColor blackColor]];
  }
  [sender setBackgroundColor:[UIColor whiteColor]];
}