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

后端 未结 11 780
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:55

    For this case, I think we could use Swift's first.where syntax, which is more efficient than filter.count, filter.isEmpty.

    Because when we use filter, it will create a underlying array, thus not effective, imagine we have a large collection.

    So just check if a view's subViews collection contains a specific kind of class, we can use this

    let containsBannerViewKind = view.subviews.first(where: { $0 is BannerView }) != nil
    

    which equivalent to: find me the first match to BannerView class in this view's subViews collection. So if this is true, we can carry out our further logic.

    Reference: https://github.com/realm/SwiftLint/blob/master/Rules.md#first-where

提交回复
热议问题