chaonextdoor
chaonextdoor

Reputation: 5139

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?

Upvotes: 16

Views: 16999

Answers (5)

F.Cartier
F.Cartier

Reputation: 1

You can do that directly through the storyboard.
Select your UITextView then in your Attributes inspector.
You have some behavior params :

enter image description here

Upvotes: -3

Jack Daniel
Jack Daniel

Reputation: 2467

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
}

Upvotes: 2

Andrew Stromme
Andrew Stromme

Reputation: 2230

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();
}

Upvotes: 5

Luis Artola
Luis Artola

Reputation: 811

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];
}

Upvotes: 14

Rafał Augustyniak
Rafał Augustyniak

Reputation: 2031

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

Upvotes: 1

Related Questions