Swift: Get all subviews of a specific type and add to an array

后端 未结 11 723
Happy的楠姐
Happy的楠姐 2020-12-13 12:25

I have a custom class of buttons in a UIView that I\'d like to add to an array so that they\'re easily accessible. Is there a way to get all subviews of a specific class and

11条回答
  •  春和景丽
    2020-12-13 12:50

    To do this recursively (I.e. fetching all subview's views aswell), you can use this generic function:

    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)
    

提交回复
热议问题