NSAttributedString的示例有两种不同的字体大小?

时间:2013-08-21 19:04:53

标签: ios nsattributedstring

NSAttributedString对我来说真的难以捉摸。

我想将UILabel设置为包含不同大小的文本,我收集NSAttributedString是可行的方法,但我无法获得有关此文档的任何内容。

如果有人能用一个具体的例子来帮助我,我会很高兴。

例如,假设我想要的文字是:

(in small letters:) "Presenting The Great..."
(in huge letters:) "HULK HOGAN!"

有人可以告诉我该怎么做吗?或者甚至是一个简单明了的参考资料,我可以为自己学习?我发誓我已经尝试通过文档来理解这一点,甚至通过Stack Overflow上的其他示例,我只是没有得到它。

5 个答案:

答案 0 :(得分:158)

你会做这样的事情......

NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Presenting the great... Hulk Hogan!"];
[hogan addAttribute:NSFontAttributeName
              value:[UIFont systemFontOfSize:20.0]
              range:NSMakeRange(24, 11)];

这将在20点文本中设置最后两个单词;字符串的其余部分将使用默认值(我认为是12分)。设置文本大小可能令人困惑的是,您必须同时设置字体大小 - 每个UIFont对象都封装了这两个属性。

答案 1 :(得分:18)

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) ]))

答案 2 :(得分:10)

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)]));

答案 3 :(得分:0)

如果你想以简单的方式做到这一点,我使用了一个名为OHAttributedLabel的git repo,它提供了NSAttributedString上的一个类别。它可以让你做以下事情:

NSMutableAttributedString *mystring = [[NSMutableAttributedString alloc] initWithString:@"My String"];
[mystring setTextColor:[UIColor colorWithRGB:78 green:111 blue:32 alpha:1]];
mystring.font = [UIFont systemFontOfSize:14];

如果您不想使用第三方库,请查看this link以获取有关如何开始使用属性字符串的体面教程。

答案 4 :(得分:0)

Swift 4.2解决方案:

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)]))
相关问题