如何遍历我的Swift视图中的所有UIButton?

mel*_*war 19 xcode ios swift

我如何UIButtons在Swift的视图中循环遍历所有内容?我想将所有标题设置为"",但我在Swift中的for循环给出了一个错误.

for btns in self.view as [UIButton] {
  // set the title to ""
}
Run Code Online (Sandbox Code Playgroud)

Woo*_*ock 35

这段代码应该有效:

for view in self.view.subviews as [UIView] {
    if let btn = view as? UIButton {
        btn.setTitleForAllStates("")
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要遍历subViews数组.


Ben*_*ess 24

缩短并更新为Swift 3和4

for case let button as UIButton in self.view.subviews {
    button.setTitleForAllStates("")
}
Run Code Online (Sandbox Code Playgroud)