【问题标题】:iterating through buttons in sender.superview遍历 sender.superview 中的按钮
【发布时间】:2015-10-09 19:12:08
【问题描述】:

我在一个视图中放置了 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 个按钮的视图。

【问题讨论】:

  • 嗯,你不能遍历单个视图?
  • @davidcao 我不确定这是修辞还是什么。无论如何,我在单个视图中迭代 x 个按钮?

标签: ios objective-c


【解决方案1】:

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

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

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

【讨论】:

  • hm,是否有必要发送 isKindOfClass 方法,因为 for 只是循环通过 UIButton 的反正?
  • @DevilInDisguise 如果您确定唯一的子视图是 UIButton 对象,那么不,根本不是。我只是不确定您的视图是否会包含其他视图类型并导致另一个意外崩溃。
  • 按最旧排序时,最上面的帖子是第一个帖子。在这个问题上是的,我的答案是第一。
【解决方案2】:

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

【讨论】:

  • 获取按钮的子视图有意义吗?我的按钮中没有任何(子)视图。
  • 我建议使用 IBOutletCollection 定义按钮的出口集合并遍历该集合。如果对象等于发件人 - 将背景颜色设置为黑色。如果没有 - 将其设置为白色。
猜你喜欢
  • 2019-12-21
  • 1970-01-01
  • 2020-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
相关资源
最近更新 更多