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