Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable UITextField editing but still accept touch?

I'm making a UITextField that has a UIPickerView as inputView. Its all good, except that I can edit by copy, paste, cut and select text, and I don't want it. Only the Picker should modify text field.

I've learned that I can disable editing by setting setEnabled or setUserInteractionEnabled to NO. Ok, but the TextField stop responding to touching and the picker don't show up.

What can I do to achieve it?

like image 494
Luiz de Prá Avatar asked Feb 02 '12 17:02

Luiz de Prá


People also ask

Can you disable editing of a text field?

editing is a readonly property. You can't set it. If it's a UITextView, it has an editable property which you can set to false.


2 Answers

Using the textfield delegate, there's a method

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 

Return NO from this, and any attempt by the user to edit the text will be rejected.

That way you can leave the field enabled but still prevent people pasting text into it.

like image 81
Nick Lockwood Avatar answered Sep 23 '22 05:09

Nick Lockwood


Translate the answer of Nick to swift:

P/S: Return false => the textfields cannot input, edit by the keyboard. It just can set text by code.EX: textField.text = "My String Here"

override func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    return false
}
like image 36
lee Avatar answered Sep 25 '22 05:09

lee