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

后端 未结 11 720
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 13:00

    Here you go

        extension UIView {
    
        /** This is the function to get subViews of a view of a particular type 
    */
        func subViews(type : T.Type) -> [T]{
            var all = [T]()
            for view in self.subviews {
                if let aView = view as? T{
                    all.append(aView)
                }
            }
            return all
        }
    
    
    /** This is a function to get subViews of a particular type from view recursively. It would look recursively in all subviews and return back the subviews of the type T */
            func allSubViewsOf(type : T.Type) -> [T]{
                var all = [T]()
                func getSubview(view: UIView) {
                    if let aView = view as? T{
                    all.append(aView)
                    }
                    guard view.subviews.count>0 else { return }
                    view.subviews.forEach{ getSubview(view: $0) }
                }
                getSubview(view: self)
                return all
            }
        }
    

    You can call it like

    let allSubviews = view.allSubViewsOf(type: UIView.self)
    let allLabels = view.allSubViewsOf(type: UILabel.self)
    

提交回复
热议问题