NSAttributedString
对我来说真的是难以理解。
我想设置一个
UILabel
来具有不同大小的文本,我认为 NSAttributedString
是可行的方法,但我无法通过此文档获得任何信息。
如果有人可以帮助我举一个具体的例子,我会很高兴。
例如,假设我想要的文本是:
(in small letters:) "Presenting The Great..."
(in huge letters:) "HULK HOGAN!"
有人可以告诉我该怎么做吗?或者甚至是一个简单明了的参考资料,我可以自己学习?我发誓我已经尝试通过文档甚至 Stack Overflow 上的其他示例来理解这一点,但我就是不明白。
假设您的输入文本是“部分文本比其余文本大”,并且您想要更改“更大”一词的大小。这样做的方法如下:
let text = NSMutableAttributedString(
"Some of this text is larger than the rest"
)
let range = text.mutableString.range(of: "larger")
if range.location != NSNotFound {
text.addAttribute(.font,
value: UIFont.systemFont(ofSize: 20),
range: range)
}
或者在 Objective-C 中,
NSMutableAttributedString *text = [[NSMutableAttributedString alloc]
initWithString:@"Some of this text is larger than the rest"];
NSRange range = [text rangeOfString:@"larger"];
if (range.location != NSNotFound) {
[text addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:20.0]
range:range];
}
具体设置文本大小可能会令人困惑的是,您必须同时设置字体 和 大小 - 每个
UIFont
对象都封装了这两个属性。
NSAttributedString.Key
的文档,了解 NSAttributedString
属性的完整列表。
Swift 3 解决方案
此外,您可以使用
append
函数而不是在 ObjC 或 Swift 中指定索引:
let attrString = NSMutableAttributedString(string: "Presenting The Great...",
attributes: [ NSFontAttributeName: UIFont.systemFont(ofSize: 20) ])
attrString.append(NSMutableAttributedString(string: "HULK HOGAN!",
attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 40) ]))
[更新] Swift 5 解决方案:
let attrString = NSMutableAttributedString(string: "Presenting The Great...",
attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18)]);
attrString.append(NSMutableAttributedString(string: "HULK HOGAN!",
attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 36)]));
Swift 4 解决方案:
let attrString = NSMutableAttributedString(string: "Presenting The Great...",
attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18)]);
attrString.append(NSMutableAttributedString(string: "HULK HOGAN!",
attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 36)]));
如果你想以简单的方式做到这一点,我使用一个名为 OHAttributedLabel 的 git 存储库,它在 NSAttributedString 上提供了一个类别。它可以让你做这样的事情:
NSMutableAttributedString *mystring = [[NSMutableAttributedString alloc] initWithString:@"My String"];
[mystring setTextColor:[UIColor colorWithRGB:78 green:111 blue:32 alpha:1]];
mystring.font = [UIFont systemFontOfSize:14];
如果您不想使用第 3 方库,请查看 此链接,获取有关如何开始使用属性字符串的不错的教程。