Swift:以递归方式遍历所有子视图以查找特定的类并追加到数组 [英] Swift: Recursively cycle through all subviews to find a specific class and append to an array
问题描述
试图弄清楚这一点有一段时间的魔鬼.我在这里问了类似的问题:迅速:获取特定类型的所有子视图并添加到数组中
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)
(在函数内递归)时,您对结果不执行任何操作.
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屋!