How to trim (remove) spaces from the end of NSAttributedString

I have a line that has no spaces at the end of the line, but when I convert to NSAttributedString and set to a UITextView , some spaces were noticed at the end of the UILabel .

To create an NSAttributedString I use the following code. In my code, expectedLabelSize is given a great height.

 UILabel *tempLbl = [[UILabel alloc]init]; tempLbl.font = txtView.font; tempLbl.text = string; NSDictionary *dictAttributes = [NSDictionary dictionaryWithObjectsAndKeys: tempLbl.font, NSFontAttributeName, aParaStyle, NSParagraphStyleAttributeName,[UIColor darkGrayColor],NSForegroundColorAttributeName, nil]; CGSize expectedLabelSize = [string boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dictAttributes context: nil].size; 
+8
ios objective-c whitespace nsattributedstring
source share
3 answers

A quick answer, but it gives you a start if you translate it to Obj-C (or create a quick file with only the extension for use in your Obj-C)

 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) } } 

Using:

 let noSpaceAttributedString = attributedString.trimmedAttributedString(set: CharacterSet.whitespacesAndNewlines) 
+7
source share

Swift 4 and above

we can create an extension for NSMutableAttributedString which returns a 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) } } 
+1
source share

try textView.textContainerInset.left = 5

-one
source share

All Articles