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

标签 ios objective-c whitespace nsattributedstring

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

最佳答案

Swift answer 但如果你将它翻译成 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)

关于ios - 如何从 NSAttributedString 的末尾修剪(删除)空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34081197/

相关文章:

ios - 使用快速枚举和 NSDictionary,不能保证按键的顺序迭代——我怎样才能让它按顺序排列?

ios - 如何将文件下载链接到进度 View

ios - Nativescript iOS 操作栏字幕

ios - dispatch_async 和帧率

notepad++ - Notepad++ 中行首的空格

PHP:str_replace() - 忽略空格

ios - 从静态库中确定目标的构建配置类型

iphone - 没有输入 Switch 语句?

iphone - 添加新按钮时旧按钮消失

python - 如何从 Python 中的字符串中删除空格?