问题
I'm using an analytics tool which logs the accessibilityLabel
of buttons.
I'm trying to find a way to update the accessibilityLabel
without changing my existing code.
For normal buttons I use the titleLabel.text
. For iconButtons which use their the name coming from image assets I use accessibilityLabel
itself.
Some issues I faced:
- can't access
accessibilityLabel
within its getter. Because that would recursively look foraccessibilityLabel
. - So I had to use another property for backing and since this was an extension I wasn't able to use stored properties. Computed properties didn't work either because it would get stuck in the same feedback loop.
- Eventually I hacked my way by using
accessibilityHint
. It's a stored property that I have no use of...
This works! Yet I've been told and read that I shouldn't override functions in an extension as that's not reliable. So I'm wondering what I should do?
And if Swift has any mechanism that doesn't involve overriding in UIButton's extension?!
here is my code:
extension UIButton{
private var adjustAccessibilityLabel : String{
if titleLabel?.text?.isEmpty == false{
return titleLabel!.text!
}else if accessibilityHint?.isEmpty == false{
return accessibilityHint!
}else{
return "Empty"
}
}
open override var accessibilityLabel: String?{
get{
return "\(self.adjustAccessibilityLabel))"
}
set{
accessibilityHint = newValue // Hacking my way through!
}
}
}
回答1:
You're fighting the system. You can achieve this using subclassing.
To avoid similar problems in the future, always have ALL your UIButton
, UITableViewCell
, UIViewController
, etc subclassed from your own base class so you can easily make such universal changes.
来源:https://stackoverflow.com/questions/50727968/how-to-modify-uibuttons-accessibilitylabel-in-an-extension