Tommy Wei Tommy Wei - 1 year ago 224
Swift Question

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?

Answer Source

Create extension of NSAttributedString as below.

extension NSAttributedString {
     public func attributedStringByTrimmingCharacterSet(charSet: NSCharacterSet) -> NSAttributedString {
         let modifiedString = NSMutableAttributedString(attributedString: self)
         return NSAttributedString(attributedString: modifiedString)

extension NSMutableAttributedString {
     public func trimCharactersInSet(charSet: NSCharacterSet) {
         var range = (string as NSString).rangeOfCharacterFromSet(charSet)

         // Trim leading characters from character set.
         while range.length != 0 && range.location == 0 {
             replaceCharactersInRange(range, withString: "")
             range = (string as NSString).rangeOfCharacterFromSet(charSet)

         // Trim trailing characters from character set.
         range = (string as NSString).rangeOfCharacterFromSet(charSet, options: .BackwardsSearch)
         while range.length != 0 && NSMaxRange(range) == length {
             replaceCharactersInRange(range, withString: "")
             range = (string as NSString).rangeOfCharacterFromSet(charSet, options: .BackwardsSearch)

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())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download