如何从 NSAttributedString 的末尾修剪(删除)空格 [英] How to trim(remove) white spaces from end of a NSAttributedString

查看:102
本文介绍了如何从 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)

这篇关于如何从 NSAttributedString 的末尾修剪(删除)空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆