Reputation: 5139
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
Reputation: 1
You can do that directly through the storyboard.
Select your UITextView
then in your Attributes inspector.
You have some behavior params :
Upvotes: -3
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
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
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
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