I hope that user can copy and paste the text but not edit them. I use a delegate UITextField
method to implement this:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
return NO;
}
In this way although the text is selectable and not editable, but when you select the text, the keyboard always shows up, which is a little bit annoying cause you can not edit the text. So is there anyway to make text selectable and not editable, without showing the keyboard?
What you need is to allow the control to receive all user interaction events. So, do not return NO
from textFieldShouldBeginEditing
. Instead, do the following:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
return textField != _yourReadOnlyTextField;
}
This will allow the user to select the text and also to select options like Cut
, Copy
and Define
from the popup menu.
UPDATE:
Also, for completeness, you may want to prevent the keyboard from showing up at all on readyonly textfields. So based on the accepted answer to this question: uitextfield hide keyboard?, you may want to add:
- (void)viewDidLoad
{
// Prevent keyboard from showing up when editing read-only text field
_yourReadOnlyTextField.inputView = [[UIView alloc] initWithFrame:CGRectZero];
}
Update for Swift users:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return textField != self.yourReadOnlyTextField;
}
and when the view loads
override func viewDidLoad() {
super.viewDidLoad()
self.selfCodeEdit.inputView = UIView.init();
}
You should implement another UITextField
's delegate method:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
return NO;
}
//UPDATE Also, there is a questions like this here How to disable UITextField's edit property?.
if you have more then one textFields you can do in this way
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == firstTextField || textField == secondTextField {
return false
}
return true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With