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?
Using the textfield delegate, there's a method
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.
For an alternative that handles the UIPickerView and Action Sheets, checkout ActionSheetPicker
https://github.com/TimCinel/ActionSheetPicker
It's cocoapods enabled. It handles all of the cancel and done buttons on the Action Sheet. The examples within the sample project are great. I choose the ActionSheetStringPicker, which handles easily just String based options, but the API can handle most anything that I can think of.
I originally started a solution much like the checkmarked answer, but stumbled onto this project and took me roughly 20 minutes to get things integrated into my app for usage including using cocopods: ActionSheetPicker (~> 0.0)
Hope this helps.
Download the git project and look at the following classes:
Here is roughly most of the code that I added, plus the *.h imports.
This worked for me
[textview setEditable:NO];
The above answers are overcomplicating the situation.It would be more elegant to create a custom subclass of
UITextField
that returnsNO
for all calls tocanPerformAction:withSender:
(or at least whereaction
is@selector(cut)
or@selector(paste)
), as described here.In addition, I'd also implement - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string as per Nick's suggestion in order to disable inputting text from Bluetooth keyboards.
Make your inputView be presented by an hidden textfield which also change the text of the presented and disabled one.
To prevent editing of UITextField while using UIPickerView for selecting values(in Swift):