Search code examples
iosobjective-cwhitespacensattributedstring

How to trim(remove) white spaces from end of a NSAttributedString


I have a string which has no whitespace at end of the string but when I am converting to NSAttributedString and set to UITextView it was seen some whitespace at end of the UILabel.

For making NSAttributedString I am using following code. In my code expectedLabelSize gives a big 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;

Solution

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