如何使UITextField可选但不可编辑?

cha*_*oor 10 objective-c uitextfield ios

我希望用户可以复制和粘贴文本,但不能编辑它们.我使用委托UITextField 方法来实现这个:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range       replacementString:(NSString *)string{
    return NO;
}
Run Code Online (Sandbox Code Playgroud)

这样虽然文本是可选择的而且不可编辑,但是当你选择文本时,键盘总是显示出来,这有点烦人,因为你无法编辑文本.那么无论如何在不显示键盘的情况下使文本可选而不可编辑?

Lui*_*ola 12

您需要的是允许控件接收所有用户交互事件.所以,不要return NO来自textFieldShouldBeginEditing.相反,请执行以下操作:

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

这将允许用户选择文本,也选择类似的选项Cut,CopyDefine从弹出菜单中.

更新:

此外,为了完整起见,您可能希望防止键盘在现成文本字段中完全显示.所以基于这个问题的接受答案:uitextfield隐藏键盘?,您可能想要添加:

- (void)viewDidLoad
{
    // Prevent keyboard from showing up when editing read-only text field
    _yourReadOnlyTextField.inputView = [[UIView alloc] initWithFrame:CGRectZero];
}
Run Code Online (Sandbox Code Playgroud)

  • 非常好.确切地说,无需更改文本即可选择和复制文本. (2认同)

ast*_*mme 5

Swift 用户的更新:

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

当视图加载时

override func viewDidLoad() {
    super.viewDidLoad()
    self.selfCodeEdit.inputView = UIView.init();
}
Run Code Online (Sandbox Code Playgroud)


Raf*_*iak 1

您应该实现 anotherUITextField的委托方法:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return NO;
}
Run Code Online (Sandbox Code Playgroud)

//更新另外,这里有一个这样的问题如何禁用 UITextField 的编辑属性?