[英]How to prevent editing of text in a UITextField without disabling other events using Swift 3?
I'm trying to modify the text rendered in the UITextField
based on certain events such as Touch Down
or Touch Down Repeat
.我正在尝试根据某些事件(例如Touch Down
或Touch Down Repeat
修改UITextField
呈现的文本。 I want the UITextField
to be responsive only to events but prevent users from modifying the actual value in the UITextField
.我希望UITextField
仅对事件做出响应,但阻止用户修改UITextField
的实际值。
I have tried unchecking the Enabled
state of the UITextField
but that causes it to not respond to touch events either.我尝试取消选中UITextField
的Enabled
状态,但这导致它也不响应触摸事件。
How do I prevent users from changing the contents of the UITextField
without affecting the response to touch events, specifically using Swift 3?如何防止用户更改UITextField
的内容而不影响对触摸事件的响应,特别是使用 Swift 3?
So, I was finally able to get this working in the expected manner.所以,我终于能够以预期的方式让它工作。 What I did was -我所做的是——
1 - Extend the UITextFieldDelegate in the ViewController
class 1 - 在ViewController
类中扩展 UITextFieldDelegate
class ViewController: UIViewController, UITextFieldDelegate {
2 - Inside the function viewDidLoad()
, assign the textfield delegate to the controller 2 - 在函数viewDidLoad()
,将文本字段委托分配给控制器
override func viewDidLoad() {
super.viewDidLoad()
textfield.delegate = self
}
(you will have assign each UITextField's delegate that you want to be prevented from editing) (您将分配要阻止编辑的每个 UITextField 委托)
3 - Lastly, implement your custom behavior in the textFieldShouldBeginEditing
function 3 - 最后,在textFieldShouldBeginEditing
函数中实现您的自定义行为
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return false
}
For reference, check outthis API Reference on Apple Developer作为参考,请查看 Apple Developer 上的此API 参考
Override textFieldShouldBeginEditing , and return false.覆盖 textFieldShouldBeginEditing ,并返回 false。
func textFieldShouldBeginEditing(state: UITextField) -> Bool {
return false
}
you can also disable for specific text field.您还可以禁用特定文本字段。
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if(textField == self.myTextField){
return false
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.