尝试切换文本字段的 isEnabled 属性,然后更改文本字段的 isEnabled 属性。
即首先禁用文本字段,然后更改文本字段的可编辑属性,然后再次启用文本字段。
希望这能解决您的问题。
我还附上了一个小代码示例:)
class ViewController: NSViewController {
let textField = NSTextField()
let button = NSButton()
override func viewDidLoad() {
textField.translatesAutoresizingMaskIntoConstraints=false
textField.placeholderString = "ENTER PROMO CODE"
button.translatesAutoresizingMaskIntoConstraints=false
super.viewDidLoad()
textField.isEditable = true
button.action = #selector(buttonClicked(_:))
view.addSubview(textField)
view.addSubview(button)
NSLayoutConstraint(item: textField, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: textField, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: textField, attribute: .width, relatedBy: .equal, toItem: nil , attribute: .notAnAttribute, multiplier: 1.0, constant: 100).isActive = true
NSLayoutConstraint(item: button, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: button, attribute: .leading, relatedBy: .equal, toItem: textField, attribute: .trailing, multiplier: 1.0, constant: 20).isActive = true
NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: nil , attribute: .notAnAttribute, multiplier: 1.0, constant: 50).isActive = true
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@objc func buttonClicked(_ sender: Any) {
textField.isEnabled = false
textField.isEditable = false
textField.isEnabled = true
}
}