在 UIView 中循环 UIButtons

Posted

技术标签:

【中文标题】在 UIView 中循环 UIButtons【英文标题】:Looping through UIButtons in UIView 【发布时间】: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")? 【参考方案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

【讨论】:

以上是关于在 UIView 中循环 UIButtons的主要内容,如果未能解决你的问题,请参考以下文章

在 for 循环中创建 CGRect 并将其分配给 UIView

链式 UIView 动画,每个动画都包含循环内的完成块 [重复]

将 UIView 移动到图像上方

iOS:从运行循环外部设置 UIView 背景颜色

iOS 10 UILabels -> 1 UIView -> 循环动画

对于在 UIView.animate 块内部或外部的循环?