如何从 NSAttributedString 的末尾修剪(删除)空格

问题描述:

我有一个字符串,它在字符串末尾没有空格,但是当我转换为 NSAttributedString 并设置为 UITextView 时,在字符串末尾看到了一些空格UILabel.

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.

为了制作 NSAttributedString 我正在使用以下代码.在我的代码中 expectedLabelSize 给出了一个很大的高度.

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;

Swift 的回答,但如果您将其转换为 Obj-C(或仅使用扩展名制作一个用于 Obj-C 的 swift 文件,它会给您一个开始然后)

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

用法:

let noSpaceAttributedString =
   attributedString.trimmedAttributedString(set: CharacterSet.whitespacesAndNewlines)