Swift: Recursively cycle through all subviews to find a specific class and append to an array

前端 未结 6 671
故里飘歌
故里飘歌 2020-12-06 04:46

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

While this works,

6条回答
  •  醉话见心
    2020-12-06 05:01

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

    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

    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
    }
    

提交回复
热议问题