本文介绍了如何在扩展中修改UIButton的accessibilityLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用记录按钮accessibilityLabel的分析工具.我正在尝试找到一种在不更改现有代码的情况下更新accessibilityLabel的方法.

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.

对于普通按钮,我使用titleLabel.text.对于使用其名称来自图像资源的iconButton,我使用accessibilityLabel本身.

For normal buttons I use the titleLabel.text. For iconButtons which use their the name coming from image assets I use accessibilityLabel itself.

我遇到的一些问题:

  • 无法在其getter中访问accessibilityLabel.因为那样会递归地查找accessibilityLabel.
  • 因此,我不得不使用另一个属性作为后盾,并且由于这是扩展,所以我无法使用存储的属性.计算属性也不起作用,因为它会卡在同一反馈循环中.
  • 最终,我使用accessibilityHint破解了自己的方式.这是我不使用的存储属性...
  • 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?

如果Swift有任何不涉及在UIButton扩展中覆盖的机制?!

And if Swift has any mechanism that doesn't involve overriding in UIButton's extension?!

这是我的代码:

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!
        }
    }
}

推荐答案

您正在与系统作战.您可以使用子类化.

You're fighting the system. You can achieve this using subclassing.

为避免将来出现类似问题,请始终将所有UIButtonUITableViewCellUIViewController等从您的 own 基类中子类化,以便您可以轻松进行此类通用更改.

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.

这篇关于如何在扩展中修改UIButton的accessibilityLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 05:10