2

In the below textView function, I append the '#' character to the end of my string every time the user presses the spacebar. However, an unwanted space comes after the appended character. I've used functions to remove whitespaces at the end of the string but those don't help. Furthermore, I also tried to remove the last character of my string using removeLast() but that just removes the '#' character itself. Please help! I'm using swift 4.2.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == " " {
        textView.text.append(("#"))
        //textView.text.removeLast()
    }
    if text == "\n" {
        textView.resignFirstResponder()
        return false
    }
    return true
}
  • 1
    Why not use a `UITextField` if the user can't type multiple lines? – rmaddy Jan 16 '19 at 20:49
  • I added that code just to silence the keyboard if the user presses return/done. – Mansur Ahmed Jan 16 '19 at 20:55
  • You missed my point. You should be using a `UITextField`, not a `UITextView`. – rmaddy Jan 16 '19 at 20:56
  • Oh, I apologize. I used a UITextView because the way I have it setup, depending on how much the user types they might end up automatically creating multiple lines. However, in this scenario, there would be no need to press return to create a new line manually. – Mansur Ahmed Jan 16 '19 at 20:59

1 Answers1

2

It's happening because you are appending the character and then returning true (in all cases except new line).

If you return false after appending the character, it should work as you want it to.

Try this:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == " " {
        textView.text.append(("#"))
        return false
    }
    if text == "\n" {
        textView.resignFirstResponder()
        return false
    }
    return true
}
Nitin Alabur
  • 5,812
  • 1
  • 34
  • 52