Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift TextView detect previous line on backspace

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading