Adrian Adrian - 2 years ago 41
iOS Question

Finding all detailDislosureButtons on a view

I'm attempting to find all buttons of a particular type (

) on a
. To find all
on a view, I'd use the following:

let buttons = view.subviews.filter{$0 is UIButton}

How would I filter by the button type, in this case a

I've tried using UIButtonType w/ raw value of 2 and with
, but I get a compiler error.

let buttons = view.subviews.filter{$0 is UIButtonType.detailDisclosure}

Thank you for reading.

Answer Source

In your filter closure you first need to check if each view is a UIButton using the conditional type cast operator (as?). If it is a button, you can then check if the buttonType property is .detailDisclosure.

let buttons = view.subviews.filter {
    guard let button = $0 as? UIButton else {
        return false
    return button.buttonType == .detailDisclosure

For an equivalent single-line solution, you can use optional chaining with the buttonType property, but note that you have to prepend the type onto .detailDisclosure (UIButtonType) because it can no longer be inferred.

buttons = view.subviews.filter { ($0 as? UIButton)?.buttonType == UIButtonType.detailDisclosure }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download