Swift:递归遍历所有子视图以查找特定类并附加到数组 [英] Swift: Recursively cycle through all subviews to find a specific class and append to an array

查看:22
本文介绍了Swift:递归遍历所有子视图以查找特定类并附加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一段时间试图解决这个问题.我在这里问了一个类似的问题:Swift:获取特定类型的所有子视图并添加到数组中

Having a devil of a time trying to figure this out. I asked a similar question here: Swift: Get all subviews of a specific type and add to an array

虽然这有效,但我意识到有很多子视图和子子视图,所以我需要一个从主 UIView 开始的函数,循环浏览所有子视图(以及它们的子视图,直到没有任何剩余)和将它添加到我命名为 CheckCircle 的自定义按钮类的数组中.

While this works, I realized there are many subviews and sub-sub views, and so I need a function that starts at the main UIView, cycles through all the subviews (and their subviews until there aren't any left) and adds it to an array for a custom button class which I have named CheckCircle.

本质上,我想最终得到一个 CheckCircles 数组,这些数组构成了以编程方式添加到该视图的所有 CheckCircles.

Essentially I'd like to end up with an array of CheckCircles which constitute all the CheckCircles added to that view programmatically.

有什么想法吗?这就是我一直在做的事情.它似乎没有将任何 Checkcircles 附加到数组中:

Any ideas? Here's what I've been working on. It doesn't seem to be appending any Checkcircles to the array:

    func getSubviewsOfView(v:UIView) -> [CheckCircle] {
        var circleArray = [CheckCircle]()
        // Get the subviews of the view

        var subviews = v.subviews

        if subviews.count == 0 {
            return circleArray
        }

        for subview : AnyObject in subviews{
  if let viewToAppend = subview as? CheckCircle {
        circleArray.append(viewToAppend as CheckCircle)
      }
            getSubviewsOfView(subview as! UIView)
        }
        return circleArray
    }

推荐答案

你的主要问题是当你调用 getSubviewsOfView(subview as! UIView)(递归地,在函数内)时,你不是t 对结果做任何事情.

Your main problem is that when you call getSubviewsOfView(subview as! UIView) (recursively, within the function), you aren't doing anything with the result.

您也可以删除 count == 0 检查,因为在这种情况下 for...in 循环将被跳过.你还有一堆不必要的演员

You also can delete the count == 0 check, since in that case the for…in loop will just be skipped. You also have a bunch of unnecessary casts

假设您希望获得 CheckCircle 实例的平面数组,我认为您的代码的这种改编应该可行:

Assuming your desire is to get a flat array of CheckCircle instances, I think this adaptation of your code should work:

func getSubviewsOfView(v:UIView) -> [CheckCircle] {
    var circleArray = [CheckCircle]()

    for subview in v.subviews as! [UIView] {
        circleArray += getSubviewsOfView(subview)

        if subview is CheckCircle {
            circleArray.append(subview as! CheckCircle)
        }
    }

    return circleArray
}

这篇关于Swift:递归遍历所有子视图以查找特定类并附加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆