首页 > 解决方案 > 当用户从 UITextfield 清除文本时禁用按钮

问题描述

第一次加载视图时,我可以禁用该按钮。即使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
    }

标签: iosswiftuitextfielduitextfielddelegate

解决方案


Add listener for your text field, for which you want to disable your action button like this in your viewDidLoad method

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

And upon call this method, check for text field is empty or not:

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

推荐阅读