Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a UITextField selectable but not editable?

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?

like image 759
chaonextdoor Avatar asked Feb 19 '14 22:02

chaonextdoor


4 Answers

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];
}
like image 130
Luis Artola Avatar answered Nov 16 '22 20:11

Luis Artola


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();
}
like image 5
Andrew Stromme Avatar answered Nov 16 '22 21:11

Andrew Stromme


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?.

like image 1
Rafał Augustyniak Avatar answered Nov 16 '22 21:11

Rafał Augustyniak


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
}
like image 1
Jack Daniel Avatar answered Nov 16 '22 22:11

Jack Daniel