【问题标题】:How to trim(remove) white spaces from end of a NSAttributedString如何从 NSAttributedString 的末尾修剪(删除)空格
【发布时间】:2015-12-04 05:00:40
【问题描述】:

我有一个字符串末尾没有空格,但是当我转换为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;

【问题讨论】:

标签: ios objective-c whitespace nsattributedstring


【解决方案1】:

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 的小改动。非常感谢
  • 这确实很好用,除非空白位于文本中间。关于如何解决这个问题的任何想法?
【解决方案2】:

Swift 4 及以上版本

我们可以在NSMutableAttributedString 上创建扩展,通过删除.whitespacesAndNewlines 返回新的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)
    }
}

【讨论】:

  • 如果字符串中的最后一个字符是表情符号,这将崩溃!
  • 我将此解决方案翻译为 ObjectiveC(根据我的需要进行了一些修改 --- 扩展 NSMutableAttributedString 并在自身上使用 'trimWhiteSpace')但我需要对在 Swift 字符串(startIndex、 upperBound 等)和原始的 NSString 和 NSRange 数字。你能详细说明一下吗?
  • 扩展 NSMutableAttributedString 而不实际允许更改它没有多大意义。此扩展更适合不可变的 NSAttributedString - 返回其自身的修剪版本。 NSMutableAttributedString 的扩展应该会影响接收到的本身 - 请参阅我的 Obj-C 扩展
【解决方案3】:
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)
    }
}

【讨论】:

    【解决方案4】:

    这是@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
    

    【讨论】:

      猜你喜欢
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 2013-09-11
      • 1970-01-01
      相关资源
      最近更新 更多