快速检测用户在 UITextView 中输入的相同占位符文本

时间:2021-07-15 12:28:58

标签: ios swift uitextview

通过将文本设置为占位符来使用 UITextView

textView.text = UIColor.black // Added in viewDidLoad

func textViewDidBeginEditing(_ textView: UITextView) {
    if (textView.text == "ADD") {
       textView.text = ""
       textView.textColor = .black
    }
}

func textViewDidEndEditing(_ textView: UITextView) {
    if (textView.text == "") {
       textView.text = "ADD"
       textView.textColor = .gray
    }
    textView.resignFirstResponder()
}

func appendBtnTap() {
     if textView.text != "" && textView.text != "ADD" {
        appendData()
     } else {
        // Show error to enter text
     }
}

以上代码工作正常,但在极端情况下,如果用户输入与占位符文本相同的文本“添加”并点击附加按钮,它将显示错误。如何避免这种情况

我从冲浪中得到的一个解决方案是检查 textColor(灰色或黑色)。这是正确的做法吗

2 个答案:

答案 0 :(得分:0)

如果文本与占位符相同,您应该使用不同的委托方法来重置文本。

textViewDidChange(_ textView: UITextView) 

答案 1 :(得分:0)

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText string: String) -> Bool { 让 oldText = txtViewDescription.text! 让 newText = (oldText as NSString).replacingCharacters(in: range, with: string)

如果旧文本 == 新文本 { 返回 }

您可以检查用户输入的旧值和新值,如果两者相同,则此委托方法返回并且什么也没发生:)