禁用编辑文本字段

Disable editing of a text field

首先我想说这是我的第一个项目,在发帖之前我正在努力寻找自己的答案。我以为我已经找到了实现这一点的代码。我没有错误,但是当我 运行 时,该字段仍然是可编辑的。那么,当我设置的规则为真时,如何禁用对我的字段的编辑?

if sport.count == 1 {

        enterSport.text = sport[0] as String //need to convert to a string
        enterSport.editing; false //do not allow editing

    } else {
        //do nothing
    }

我之前已经定义了数组,因此 if 语句为真。谢谢你的帮助。

enterSport.userInteractionEnabled = false 而不是 editing.

editing 是一个只读 属性 以指示当前是否正在编辑该字段。

Swift 5: enterSport.isUserInteractionEnabled = false

总结以上回答和评论:

编辑是只读的属性。你不能设置它。

如果它是 UITextView,它有一个可编辑的 属性,您可以将其设置为 false。

如果是 UITextField,您需要使用已启用的 属性 或 userInteractionEnabled 属性。其中任何一个都会阻止编辑。作为

使用 Swift 3 Apple 将 属性 userInteractionEnabled 更改为 isUserInteractionEnabled

代码如下所示:

textfield.isUserInteractionEnabled = true

还有一种方法可以避免键盘出现

您可以像这样设置 UITapGestureRecognizer

let tap = UITapGestureRecognizer(target: self, action: #selector(self.textFieldEditing))
self.enterSport.addGestureRecognizer(tap)

@objc func textFieldEditing() {
    self.enterSport.resignFirstResponder()
    
}