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

标签 ios swift uitextfield uitextfielddelegate

我可以在第一次加载 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/

相关文章:

ios - 后台期间的 EAAccessory/EASession 拆卸

swift - AVQueuePlayer 视频在 Swift 中不起作用

ios - 如何实现占位符文本在 UITextField 中逐字符消失

ios - UITableView 单元格标题传输到另一个 View 上的 Uitextfield

ios - 快速从结构数据中提取字节

ios - xamarin 中的等效 customHTTPProtocol

ios - 如何在没有导航 Controller 的情况下导航到另一个 Controller ?

ios - Swift:将 "addTarget"应用于不同类中的 UIButton

ios - 解析 : PFObject is loaded without Attributes

swift - 找出 UIKeyboard.frame 何时与其他框架相交?