How to delete Whitespace from textview in the end and also delete white space from enter keys in swift2.0

477 Views Asked by At

I am new to swift.I want to delete white space and also delete new line white space from TextView.So please advice.

Thanks in advance.

1

There are 1 best solutions below

0
Sahil_Saini On BEST ANSWER

For new line or when the enter button is pressed you can use the delegate method

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool

add this to the method if text == "\n" { self.view.endEditing(true) return false }

For whitespace in the end use the below code.

var stringFromText = textView.text

    var lastChar = stringFromText.characters.last


    while lastChar == " " {
        stringFromText = String(stringFromText.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()))
        print(stringFromText!)
       if stringFromText != "" {
            lastChar = stringFromText?.characters.last
        }
        else
        {
            lastChar = "A" //Any random char
        }

        print(lastChar!)
    }
    textComment.text = stringFromText

Hope it helps.