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

Le *_*ced 79 nsattributedstring ios

NSAttributedString 对我来说真是难以捉摸.

我想设置一个UILabel具有不同大小的文本,我收集的NSAttributedString是要走的路,但我无法获得任何关于此的文档.

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

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

(in small letters:) "Presenting The Great..."
(in huge letters:) "HULK HOGAN!"
Run Code Online (Sandbox Code Playgroud)

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

bde*_*ham 161

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

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

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


ilj*_*ljn 19

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) ]))
Run Code Online (Sandbox Code Playgroud)


Kun*_*hah 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)]));
Run Code Online (Sandbox Code Playgroud)