【问题标题】:Add didSet observer on a weak property in an extension在扩展中的弱属性上添加 didSet 观察者
【发布时间】:2015-11-19 23:57:07
【问题描述】:

我正在尝试制作一个 UITextField 扩展,它在设置委托时执行附加功能。

extension UITextField {
    override weak public var delegate: UITextFieldDelegate? {
        didSet {
            print("Do stuff")

        }  
    }
}

这会失败并出现三个错误:

'delegate' used within its own type

'weak' cannot be applied to non-class type '<<error type>>'

Property does not override any property from its superclass

我需要更改哪些Do stuff 才能在委托设置时打印?

【问题讨论】:

    标签: ios swift delegates uitextfield


    【解决方案1】:

    您不能使用扩展覆盖委托属性,您需要创建子类:

    class TextField: UITextField {
        override weak var delegate: UITextFieldDelegate? {
            didSet {
                super.delegate = delegate
                print("Do stuff")
            }
        }
    }
    

    但这似乎有点不对劲。你想达到什么目的?

    【讨论】:

    • 最终,我试图了解如何按顺序调用多个代表(而不是仅限于一个)。然而,无论如何,观察者模式在这种情况下更强大。
    猜你喜欢
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多