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

后端 未结 11 742
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:57

    The filter function using the is operator can filter items of a specific class.

    let myViews = view.subviews.filter{$0 is MyButtonClass}
    

    MyButtonClass is the custom class to be filtered for.

    To filter and cast the view to the custom type use compactMap

    let myViews = view.subviews.compactMap{$0 as? MyButtonClass}
    

提交回复
热议问题