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

后端 未结 11 710
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:47

    Let me post my variation of this) but this, finds the first of T

    extension UIView {
    
        func firstSubView(ofType type: T.Type) -> T? {
            var resultView: T?
            for view in subviews {
                if let view = view as? T {
                    resultView = view
                    break
                }
                else {
                    if let foundView = view.firstSubView(ofType: T.self) {
                        resultView = foundView
                        break
                    }
                }
            }
            return resultView
        }
    }
    

提交回复
热议问题