简体   繁体   中英

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 . I want the UITextField to be responsive only to events but prevent users from modifying the actual value in the UITextField .

I have tried unchecking the Enabled state of the UITextField but that causes it to not respond to touch events either.

How do I prevent users from changing the contents of the UITextField without affecting the response to touch events, specifically using 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

class ViewController: UIViewController, UITextFieldDelegate {

2 - Inside the function viewDidLoad() , assign the textfield delegate to the controller

override func viewDidLoad() {
    super.viewDidLoad()
    textfield.delegate = self
}

(you will have assign each UITextField's delegate that you want to be prevented from editing)

3 - Lastly, implement your custom behavior in the textFieldShouldBeginEditing function

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
    return false
}        

For reference, check outthis API Reference on Apple Developer

Override textFieldShouldBeginEditing , and return 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM