Search code examples
swift2ios7.1xcode7.3

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


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.


Solution

  • 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.