如何遍历Swift视图中的所有UIButtons?
在Swift中,我将如何遍历所有的UIButtons
? 我想将所有的标题设置为""
,但我在Swift中的for循环给出了一个错误。
for btns in self.view as [UIButton] { // set the title to "" }
这个代码应该工作:
for view in self.view.subviews as [UIView] { if let btn = view as? UIButton { btn.setTitleForAllStates("") } }
您需要遍历子视图数组。
缩短和更新Swift 3
for case let button as UIButton in self.view.subviews { button.setTitleForAllStates("") }
在Swift 2 / Swift 3中可以更简化
for case let button as UIButton in self.view.subviews { button.setTitleForAllStates("") }
有关更多信息,请参阅Swift语言参考中的模式 。
循环子视图的作品,但有时有点难看,还有其他问题。
如果您需要循环使用某些特定的button,例如添加圆angular半径或更改色调或背景颜色,则可以使用一组IBOutlet,然后对其进行循环。
var buttons = [SkipBtn, AllowBtn] for button in buttons as! [UIButton] { button.layer.cornerRadius = 5 }
这段代码似乎对遍历视图内的任何对象都是非常有用的,只需将UIButton更改为任何其他子视图types,例如UIView或UIImageView等。
let filteredSubviews = self.view.subviews.filter({ $0.isKindOfClass(UIButton)}) for view in filteredSubviews { //Do something }
使用一些提供的问题,并创build自己的。 我相信是最有效的,当你想以编程方式设置各种UIButtons
的标题(在我的情况下,我正在build设一个测验)
通过randomising
我的数组列表,并只是一个for循环我打印索引项目的button标题
for view in self.viewForButtons.subviews{ if view.isKindOfClass(UIButton) { let button : UIButton = view as! UIButton button.setTitle("item[i]", forState: .Normal) } }
如果你知道子视图只有button,这里有一个简短的方法在Swift中:
myView.subviews.map { ($0 as? UIButton)!.enabled = false }