我的设置如下:
UIView(1) - > UIScrollview - > UIStackview - > UIViews(2) - >的UIButton
如何遍历UIStackview中所有UIViews(2)中的每个UIButton?我的UIView(1)中有更多按钮,所以我无法遍历整个Viewcontroller中的每个按钮。我试过了:
for view in self.stackview.subviews as [UIView] {
if let btn = view as? UIButton {
print("Worked")
}
}
for view in self.scrollview.subviews as [UIView] {
if let btn = view as? UIButton {
print("Worked")
}
}
for case let button as UIButton in self.scrollview.subviews {
print("worked")
}
for case let button as UIButton in self.stackview.subviews {
print("worked")
}
尝试在我的viewDidLoad函数中添加此内容时,它不会打印任何内容。我在这里做错了什么?
答案 0 :(得分:6)
首先想到的解决方案:
let buttons = self.stackview.subviews // direct subviews of stack view
.map { subview in subview.subviews } // second level subviews
.joined() // join the second level subviews into one flat array
.compactMap { $0 as? UIButton } // filter buttons
基本上你只是忘了跳到第二级。您只迭代第一级子视图。
如果你想要一个更稳定的解决方案,你可以在任何深度的子视图上递归迭代,例如使用类别:
extension UIView {
var allSubviews: [UIView] {
return self.subviews + self.subviews.map { $0.allSubviews }.joined()
}
}
然后
let buttons = self.stackview.allSubviews.compactMap { $0 as? UIButton }
答案 1 :(得分:1)
怎么样......
for view in stackView.subviews {
for case let button as UIButton in view.subviews {
print(button.title(for: .normal)) // Do something with button
}
}
或
for case let button as UIButton in stackView.subviews.flatMap({ $0.subviews }) {
print(button.title(for: .normal)) // Do something with button
}
或
for button in stackView.subviews.flatMap({ $0.subviews }).flatMap({ $0 as? UIButton }) {
print(button.title(for: .normal)) // Do something with button
}