iosswiftcocoa-touch

Swift NSAttributedString Trim


I want to get ride of the white spaces in front and at the end of my NSAttributedString(Trimming it). I can't simply convert it to string and do trimming because there are images(attachments) in it. How can i do it?


Solution

  • Create extension of NSAttributedString as below.

    extension NSAttributedString {
         public func attributedStringByTrimmingCharacterSet(charSet: CharacterSet) -> NSAttributedString {
             let modifiedString = NSMutableAttributedString(attributedString: self)
            modifiedString.trimCharactersInSet(charSet: charSet)
             return NSAttributedString(attributedString: modifiedString)
         }
    }
    
    extension NSMutableAttributedString {
         public func trimCharactersInSet(charSet: CharacterSet) {
            var range = (string as NSString).rangeOfCharacter(from: charSet as CharacterSet)
    
             // Trim leading characters from character set.
             while range.length != 0 && range.location == 0 {
                replaceCharacters(in: range, with: "")
                range = (string as NSString).rangeOfCharacter(from: charSet)
             }
    
             // Trim trailing characters from character set.
            range = (string as NSString).rangeOfCharacter(from: charSet, options: .backwards)
             while range.length != 0 && NSMaxRange(range) == length {
                replaceCharacters(in: range, with: "")
                range = (string as NSString).rangeOfCharacter(from: charSet, options: .backwards)
             }
         }
    }
    

    and use in viewController where you want to use. like this

    let attstring = NSAttributedString(string: "this is test message. Please wait.                   ")
    let result = attstring.attributedStringByTrimmingCharacterSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())