how to modify UIButton's accessibilityLabel in an extension

浪尽此生 提交于 2019-12-25 00:25:44

问题


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 for accessibilityLabel.
  • 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!