在扩展的弱属性上添加didSet观察者

时间:2015-11-19 23:57:07

标签: ios swift delegates uitextfield

我正在尝试创建一个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才能打印?

1 个答案:

答案 0 :(得分:2)

您无法使用扩展名覆盖委托属性,您需要创建子类:

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

但这似乎有点不对劲。你想要实现什么目标?