0

Problem: while placeholder is shown:

  1. Paste insert mess inside placeholder with placeholder color
  2. You can select part of the placeholder and copy it, etc

Saw all suggestions here and got some delegate UITextViewDelegate code:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    // if try to paste placeholder - ban
    if text == placeholderText {
        return false
    }
    // if paste in placeholder do some trick
    if textView.text == placeholderText {
        textView.textColor = .label
        if text.count > 0 {
            textView.text = text
            return false
        }
        textView.text = ""
    }
    return true
}

// not allow selecting placeholder
func textViewDidChangeSelection(_ textView: UITextView) {
    // if they try to select placeholder
    if textView.selectedRange.length > 0 && textView.text == placeholderText {
        textView.textColor = .label
        textView.text = ""
    }
}

// restore placeholder when empty
func textViewDidEndEditing(_ textView: UITextView) {
    if textView.text.isEmpty {
        textView.textColor = .placeholderText
        textView.text = placeholderText
    }
}

Looks like pinned with nails. Would like to hear any suggestions / improvements

1 Answers1

0

Have you tried the solution on this post?

If you want to clear the placeholder text as soon as the user selects it (which is what it looks like from your code), you should be able to achieve your goal using only the textViewDidBeginEditing and textViewDidEndEditing delegate methods. The solution I linked includes example bodies for both methods.

mimo
  • 247
  • 1
  • 7