如何 trim(删除)NSAttributedString 末尾的空格

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

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

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

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(或者制作一个 swift 文件,然后只使用扩展名在你的 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)
    }
}

用法:

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

Swift 4岁以上

我们可以通过删除 .whitespacesAndNewlines

NSMutableAttributedString 上创建 returns 新 NSAttributedString 的扩展
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)
    }
}
extension NSAttributedString {
    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?.lowerBound, let endLocation = endRange?.lowerBound else {
            return self
        }
        let range = NSRange(startLocation...endLocation, in: string)
        return attributedSubstring(from: range)
    }
}

这是 @suhit Patil 的 Swift NSAttributedString 扩展的 Obj-C 渲染 - 但这次,它在 NSMutableAttributedString 上并作用于自身。希望对大家有用。

@interface NSMutableAttributedString (OITTrimming)

- (void)trimWhiteSpace;

@end

@implementation NSMutableAttributedString (OITTrimming)

 /*!
  @abstract trims whitespacesAndNewlines off the receiver
*/
- (void)trimWhiteSpace {
    NSCharacterSet *legalChars = [[NSCharacterSet whitespaceAndNewlineCharacterSet] invertedSet];
    NSRange startRange = [self.string rangeOfCharacterFromSet: legalChars];
    NSRange endRange = [self.string rangeOfCharacterFromSet: legalChars options:NSBackwardsSearch];
    if (startRange.location == NSNotFound || endRange.location == NSNotFound) {
        // there are no legal characters in self --- it is ALL whitespace, and so we 'trim' everything leaving an empty string
        [self setAttributedString:[NSAttributedString new]];
    }
    else {
        NSUInteger startLocation = NSMaxRange(startRange), endLocation = endRange.location;
        NSRange range = NSMakeRange(startLocation - 1, endLocation - startLocation + 2);
        [self setAttributedString:[self attributedSubstringFromRange:range]];
    }
}

@end