Home > Blockchain >  Swift TextView detect previous line on backspace
Swift TextView detect previous line on backspace

Time:12-07

Problem:

I need to detect when backspace is tapped and goes back to the previous line.

How can we detect a backspace that brings us back to a previous line on a textview, NOT a new line but the previous line.

For example: We can detect a new line by the given code

if (text == "\n"){
   print("new line")
 }

We can detect a backspace.

if (range.length == 1 && text.isEmpty){
       print("backspace pressed on keyboard") 
 }

Pseudo code: How can we detect a backspace that brings us back to a previous line on a textview, NOT a new line but the previous line.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

if (range.length == 1 && text.isEmpty){
       print("backspace pressed on keyboard")
       if (backspace brought textview cursor back to its previous line){

       }

}

Inputs on Keyboard:

return pressed -> bring us to new line

backspace pressed -> returns us to prev line

CodePudding user response:

Given your overly simplistic examples you can check to see if the current text in the text view at the changed range is equal to a newline character.

if (textView.text as NSString).substring(with: range) == "\n" {

Keep in mind that text in a text view can wrap without ever entering a newline character. That may or may not be important for your use case. And this also means that the text can "unwrap" without deleting a newline character.

You seem to be assuming that the cursor is at the end of the text. Not sure how you want to handle the user deleting somewhere in the middle. Or what about a user selecting a bunch of text and deleting?

Also note that your check for a backspace isn't really a check for a backspace. That condition can also be met if the user selects one character and then selects the Cut menu.

  • Related