search

Home  >  Q&A  >  body text

objective-c - 关于遍历 View 上所有的 UIButton 的问题,求问

关于遍历 View 上所有的 UIButton 的问题,求问

for (id obj in self.view.subviews) {
if ([obj isKindOfClass:[UIButton Class]]) {
UIButton theButton = (UIButton)obj;
theButton.xxx = ooo;
}
}

为什么在控件上遍历子控件时我们要在 for in 中取 id 属性再做 if ([obj isKindOfClass:[UIButton Class]])判断而不能直解取 uibutton ,像下面这样:

for (id obj in self.view.subviews) {
UIButton theButton = (UIButton)obj;
theButton.xxx = ooo;

}

某草草某草草2761 days ago644

reply all(4)I'll reply

  • 高洛峰

    高洛峰2017-04-28 09:06:24

    You are not directly taking UIButton, or I misunderstood, you are explicitly converting the type.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-04-28 09:06:24

    There is not necessarily only UIButton in the subview, but there can also be other controls. You are forcing all controls to UIButton, which is very dangerous and will crash if you are not careful.
    The safe way is to first determine whether the obtained control is a UIButton, and then force conversion. The control type at this time is actually already known. Force conversion is just to use the methods and properties of UIButton without reporting an error.
    In addition, id is not an attribute, dear, it is a special type of oc, you can think of it as object. Any object can be typed with it.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-28 09:06:24

    That’s because your self.view does not necessarily only have buttons. What should you do if there is a label inside when you use uibutton to force transfer? It will report an error.

    reply
    0
  • 滿天的星座

    滿天的星座2017-04-28 09:06:24

    Unless you make sure that all subviews of the view are button types, you will definitely make mistakes when you press the donkey head on the human body.

    reply
    0
  • Cancelreply