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

Vvk*_*Vvk 11 whitespace objective-c nsattributedstring ios

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

为了使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;
Run Code Online (Sandbox Code Playgroud)

Dea*_*ean 14

快速回答但是如果你将它翻译成Obj-C(或者只是使用你的Obj-C中使用的扩展名制作一个swift文件)它会给你一个开始

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

let noSpaceAttributedString =
   attributedString.trimmedAttributedString(set: CharacterSet.whitespacesAndNewlines)
Run Code Online (Sandbox Code Playgroud)


Suh*_*til 7

Swift 4及以上

我们可以创建扩展在NSMutableAttributedString其返回新NSAttributedString通过去除.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)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果字符串中的最后一个字符是表情符号,这将会崩溃! (2认同)