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

前端 未结 6 673
故里飘歌
故里飘歌 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

    My approach with swift 3 and generics!

    private func getSubviewsOf(view: UIView) -> [T] {
        var subviews = [T]()
    
        for subview in view.subviews {
            subviews += getSubviewsOf(view: subview) as [T]
    
            if let subview = subview as? T {
                subviews.append(subview)
            }
        }
    
        return subviews
    }
    

    To fetch all UILabel's in a view hierarchy, just do this:

    let allLabels: [UILabel] = getSubviewsOf(view: theView)
    

提交回复
热议问题