![](/img/trans.png)
[英]Prevent editing UITextField but not the user interaction in Swift
[英]How to prevent editing of text in a UITextField without disabling other events using Swift 3?
我正在尝试根据某些事件(例如Touch Down
或Touch Down Repeat
修改UITextField
呈现的文本。 我希望UITextField
仅对事件做出响应,但阻止用户修改UITextField
的实际值。
我尝试取消选中UITextField
的Enabled
状态,但这导致它也不响应触摸事件。
如何防止用户更改UITextField
的内容而不影响对触摸事件的响应,特别是使用 Swift 3?
所以,我终于能够以预期的方式让它工作。 我所做的是——
1 - 在ViewController
类中扩展 UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate {
2 - 在函数viewDidLoad()
,将文本字段委托分配给控制器
override func viewDidLoad() {
super.viewDidLoad()
textfield.delegate = self
}
(您将分配要阻止编辑的每个 UITextField 委托)
3 - 最后,在textFieldShouldBeginEditing
函数中实现您的自定义行为
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}
作为参考,请查看 Apple Developer 上的此API 参考
覆盖 textFieldShouldBeginEditing ,并返回 false。
func textFieldShouldBeginEditing(state: UITextField) -> Bool {
return false
}
您还可以禁用特定文本字段。
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if(textField == self.myTextField){
return false
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.