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

后端 未结 11 725
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:51

    From Swift 4.1, you can use new compactMap (flatMap is now depcrecated): https://developer.apple.com/documentation/swift/sequence/2950916-compactmap (see examples inside)

    In your case, you can use:

    let buttons:[UIButton] = stackView.subviews.compactMap{ $0 as? UIButton }
    

    And you can execute actions to all buttons using map:

    let _ = stackView.subviews.compactMap{ $0 as? UIButton }.map { $0.isSelected = false }
    

提交回复
热议问题