UITextView 中的 UITextField 函数不可用

UITextField function not available in UITextView

我在根据 textView 应用 textField 函数时遇到问题。

以前,我使用的是 textField,下面的代码 运行 很顺利,没有任何问题。现在,我决定使用 textView 而不是 textField,所以想将每个 textField 更改为 textView 但不知道如何将 textField.addtarget() 函数实现到 textView。我想要的是,最初,当 textView 为空时,按钮颜色未启用,但当其中有文本时,按钮颜色应为蓝色。

我找不到包含 #selector 的适当函数来调用 textView 函数中的主函数。我将不胜感激任何帮助。非常感谢您!

 override func viewDidLoad() {
    super.viewDidLoad()
    buttonColor.isEnabled = false    
    handleTextField()
}


func handleTextField() {

    textField.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControlEvents.editingChanged)
}   // used to call the main function



@objc func textFieldDidChange() {

if (textView.text != ""){
        buttonColor.setTitleColor(UIColor.blue, for: UIControlState.normal)
        buttonColor.isEnabled = true
        return
    }
    buttonColor.setTitleColor(UIColor.lightGray, for: UIControlState.normal)
    buttonColor.isEnabled = false
} 

您在 UITextViewDelegate 中有一个名为 textViewDidChange(_:) 的代表。

class ViewController: UIViewController, UITextViewDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        yourTextView.delegate = self
        print(locationName)   // not important
        buttonColor.isEnabled = false    // not important
    }

    //Your other code

    func textViewDidChange(textView: UITextView) {
        if (textView.text != ""){
            buttonColor.setTitleColor(UIColor.blue, for: UIControlState.normal)
            buttonColor.isEnabled = true
            return
        }
        buttonColor.setTitleColor(UIColor.lightGray, for: UIControlState.normal)
        buttonColor.isEnabled = false
    }
}