gpt4 book ai didi

ios - 当用户清除 UITextfield 中的文本时禁用按钮

转载 作者:行者123 更新时间:2023-11-28 10:06:13 24 4
gpt4 key购买 nike

我可以在第一次加载 View 时禁用按钮。即使 textfield 为空。但是在发送消息后,当我从 textfield 中键入并删除文本时,它不起作用。 button 交互仍然有效,用户可以发送不需要的空消息。我仍然希望在用户键入和删除文本时禁用该按钮,以防他们改变主意。这是我的代码。

@IBOutlet weak var textField: UITextField!
@IBOutlet weak var sendButton: UIButton!

override func viewDidLoad() {
super.viewDidLoad()
self.textField.delegate = self
if textField.text!.isEmpty {
sendButton.isUserInteractionEnabled = false
}
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let inputText = (textField.text! as NSString).replacingCharacters(in: range, with: string)

if !inputText.isEmpty {
sendButton.isUserInteractionEnabled = true
} else {
sendButton.isUserInteractionEnabled = false
}
return true
}

最佳答案

为您的文本字段添加监听器,您希望在您的 viewDidLoad 方法中禁用您的操作按钮

textField.addTarget(self, action: #selector(actionTextFieldIsEditingChanged), for: UIControlEvents.editingChanged)

调用此方法后,检查文本字段是否为空:

@objc func actionTextFieldIsEditingChanged(sender: UITextField) {
if sender.text.isEmpty {
sendButton.isUserInteractionEnabled = false
} else {
sendButton.isUserInteractionEnabled = true
}
}

关于ios - 当用户清除 UITextfield 中的文本时禁用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53081680/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com