2014-02-19 32 views
6

我希望用户可以复制和粘贴文本,但不能编辑它们。我使用委托UITextField方法来实现这一点:如何使UITextField可选但不可编辑?

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range  replacementString:(NSString *)string{ 
    return NO; 
} 

这样虽然文本是可选择的和不可编辑的,但是当你选择文本,键盘始终显示出来,这是一个有点恼人,因为你无法编辑文字。那么无论如何要让文本可选而不可编辑,而不显示键盘?

+0

您是否尝试过在'delegate'方法中首先调用'[textField resignFirsResponder]'。坦率地说,我不知道它会如何表现。只是问问。 –

+0

你也可以尝试子类UITextField - 重写'becomeFirstResponder1方法并返回'NO,但我认为这将阻止用户粘贴文本。 –

回答

1

你应该实现另一个UITextField的委托方法:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{ 
    return NO; 
} 

// UPDATE此外,还有这样这里How to disable UITextField's edit property?一个问题。

+0

这将不允许用户粘贴文本。看看在这里接受的答案应该工作的解决方案:http://stackoverflow.com/questions/5478719/uitextfield-hide-keyboard – TheEye

+1

我试过这个。但是这个文本既不可选也不可编辑,就像UIlabel一样。 – chaonextdoor

+0

@TheEye谢谢你!它像一个魅力。 – chaonextdoor

10

您需要的是允许控件接收所有用户交互事件。所以,请从textFieldShouldBeginEditing请勿return NO。相反,做到以下几点:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    return textField != _yourReadOnlyTextField; 
} 

这将允许用户选择文本,并选择喜欢CutCopyDefine从弹出菜单中选择。

UPDATE:

而且,完整性,您可能要防止键盘显示出来,在所有的readyonly文本框。因此,基于所接受的回答了这个问题:uitextfield hide keyboard?,你可能要添加:

为SWIFT用户
- (void)viewDidLoad 
{ 
    // Prevent keyboard from showing up when editing read-only text field 
    _yourReadOnlyTextField.inputView = [[UIView alloc] initWithFrame:CGRectZero]; 
} 
+2

非常好。究竟需要什么才能选择和复制文本而不改变文本。 – James

+0

好的解决方案,但文本光标仍然存在。 – Toydor

+0

我的文本字段在UITableViewCell中,所以我查了 return textfield.tag!= 200 – Yaman

1

更新:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
    return textField != self.yourReadOnlyTextField; 
} 

当视图加载

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.selfCodeEdit.inputView = UIView.init(); 
} 
0

如果你有多于一个textFields你可以这样做

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { 
    if textField == firstTextField || textField == secondTextField { 
     return false 
    } 
    return true 
} 
相关问题