I'm attempting to find all buttons of a particular type ( detailDisclosure
) on a UIViewController
. To find all UIButtons
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 detailDisclosure
?
I've tried using UIButtonType w/ raw value of 2 and with UIButtonType.detailDisclosure
, but I get a compiler error.
let buttons = view.subviews.filter{$0 is UIButtonType.detailDisclosure}
Thank you for reading.
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 }
Try this ....
let buttons = view.subviews.filter { (v) -> Bool in
if let btn = v as? UIButton {
if btn.buttonType == .detailDisclosure {
return true
}
}
return false
}
This is swift 2.3 but you can do something like this in your filter method
if buton.buttonType == UIButtonType.DetailDisclosure {
}
This one is working for me perfectly: (Swift 3)
let buttons = view.subviews.filter{$0 is UIButton}
for btn in buttons as! [UIButton] {
if btn.buttonType == .detailDisclosure {
print(bin)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.