Search code examples
iosswiftuitextfielddelegate

how can I make a particular textfield uneditable when using shouldChangeCharactersInRange function


I am working on my sign up page that has 4 text fields. One of the text fields works as Picker-view, when users tap on it a picker-view will pop up with options to choose from.

The question is how can I make that particular textfield uneditable? (not all of the the text fields).

I tried using

func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {

return false
}

but the problem is that it made all my text fields uneditable.

I also can't use textField.userInteractionEnabled = false, because then I wont be able to tap on the textfield to show the picker-view.

thank you.


Solution

  • You can keep a reference to the text field and compare against it in your delegate method:

    func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
        if textField == self.myTextField {
             return false 
        }
        return true
    }
    

    Another option that I've employed is to place a UIView over top of the text field with a gesture recognizer to intercept the the touch and call the picker or perform whatever code you want performed on touching the field.