Ameya Pandilwar
Ameya Pandilwar

Reputation: 2778

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?

Upvotes: 2

Views: 1771

Answers (2)

Ameya Pandilwar
Ameya Pandilwar

Reputation: 2778

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 out this API Reference on Apple Developer

Upvotes: 2

RavikanthM
RavikanthM

Reputation: 598

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;
}

Upvotes: 0

Related Questions