Mar*_*ius 6 cocoa-touch objective-c uitextfield ios uitextfielddelegate
我正在尝试创建一个能够响应以下内容的文本字段:
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
Run Code Online (Sandbox Code Playgroud)
为此,我有一个UITextField子类,它是自己的委托:
[self setDelegate:self]
Run Code Online (Sandbox Code Playgroud)
问题:在子类中实现委托方法的最简单方法是什么,但仍允许外部对象成为委托并收到相同的消息?
谢谢
Pau*_*tos 14
我遇到了完全相同的问题(在Swift 3中).我解决了这个问题压倒一切的delegate从属性UITextField类.
在我的自定义视图初始化期间,我连接了自己的内部委托:
class CustomTextField: UITextField, UITextFieldDelegate {
override public init(frame: CGRect) {
super.init(frame: frame)
initCustomTextField()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initCustomTextField()
}
private func initCustomTextField() {
super.delegate = self // Note the super qualifier.
}
...
Run Code Online (Sandbox Code Playgroud)
现在我们需要覆盖上述delegate属性:
private weak var userDelegate: UITextFieldDelegate?
override var delegate: UITextFieldDelegate? {
get { return userDelegate }
set { userDelegate = newValue }
}
Run Code Online (Sandbox Code Playgroud)
最后,在每个UITextFieldDelegate协议方法上,您必须将调用转发给外部委托,如果有的话:
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
// Do your thing here, and then forward:
return self.delegate?.textFieldShouldBeginEditing?(self) ?? true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
// Do your thing here, and then forward:
self.delegate?.textFieldDidBeginEditing?(self)
}
...
Run Code Online (Sandbox Code Playgroud)
如果您打算同时支持iOS 10,还有一点需要注意:
func textFieldDidEndEditing(_ textField: UITextField) {
self.delegate?.textFieldDidEndEditing?(self)
}
/// This method will be called, instead of the above, on iOS ? 10.
@available(iOS 10.0, *)
func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
self.delegate?.textFieldDidEndEditing?(self, reason: reason)
}
Run Code Online (Sandbox Code Playgroud)
您可以利用Notifications. 使其成为文本字段发布通知,如下所示:
[[NSNotificationCenter defaultCenter] postNotificationName:@"custom notification name" object:self];
Run Code Online (Sandbox Code Playgroud)
并将观察者添加到应该是外部委托的类中:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cacheUpdated:) name:@"custom notification name" object:nil];
Run Code Online (Sandbox Code Playgroud)
这样,文本字段发布通知,这意味着它采取了某种操作,并且您的外部委托类将收到通知,因为它已经在侦听此类通知。希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
2819 次 |
| 最近记录: |