【问题标题】:Looping through UIButtons in UIView在 UIView 中循环 UIButtons
【发布时间】:2017-03-06 15:22:37
【问题描述】:

我的设置如下:

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 函数中添加它时,它只是不打印任何内容。我在这里做错了什么?

【问题讨论】:

  • for view in self.stackview.subviews as [UIView] { if let btn = view as? UIButton { print("Worked")} else for asubView in view.subviews as [UIView]{if let btn = view as? UIButton { print("Worked")}}}?

标签: ios swift loops


【解决方案1】:

想到的第一个解决方案:

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 }

【讨论】:

  • 谢谢,这对于制作 for in 循环非常有用!
  • 很酷的函数式解决方案。 (已投票)
【解决方案2】:

怎么样……

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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 2012-05-21
    相关资源
    最近更新 更多