How to trim(remove) white spaces from end of a NSAttributedString
Swift answer but it give you a start if you translate it to Obj-C (or make a swift file just with the extension for use in your Obj-C then)
extension NSMutableAttributedString {
func trimmedAttributedString(set: CharacterSet) -> NSMutableAttributedString {
let invertedSet = set.inverted
var range = (string as NSString).rangeOfCharacter(from: invertedSet)
let loc = range.length > 0 ? range.location : 0
range = (string as NSString).rangeOfCharacter(
from: invertedSet, options: .backwards)
let len = (range.length > 0 ? NSMaxRange(range) : string.characters.count) - loc
let r = self.attributedSubstring(from: NSMakeRange(loc, len))
return NSMutableAttributedString(attributedString: r)
}
}
Usage :
let noSpaceAttributedString =
attributedString.trimmedAttributedString(set: CharacterSet.whitespacesAndNewlines)
Swift 4 and above
we can create extension on NSMutableAttributedString
which returns new NSAttributedString
by removing .whitespacesAndNewlines
extension NSMutableAttributedString {
func trimmedAttributedString() -> NSAttributedString {
let invertedSet = CharacterSet.whitespacesAndNewlines.inverted
let startRange = string.rangeOfCharacter(from: invertedSet)
let endRange = string.rangeOfCharacter(from: invertedSet, options: .backwards)
guard let startLocation = startRange?.upperBound, let endLocation = endRange?.lowerBound else {
return NSAttributedString(string: string)
}
let location = string.distance(from: string.startIndex, to: startLocation) - 1
let length = string.distance(from: startLocation, to: endLocation) + 2
let range = NSRange(location: location, length: length)
return attributedSubstring(from: range)
}
}