如何以粗体显示字符串(不带NSMutableString)

时间:2014-05-01 19:11:05

标签: nsstring string-formatting

看起来很明显,但我没有找到答案: - (...

有没有人知道我们如何定义新的NSString并将其设置为粗体(或斜体)。我知道我们可以使用Attributed的东西来做,但问题是我明白我们需要NSMutableString然后我不能将这个MutableString转换为NSString(稍后在[NSString stringWithFormat ...]中使用它)尽管在某处看到了一些命题。

(我正在生成PDF并且还没有发现在文档中使用粗体字符串的其他方法。)

1 个答案:

答案 0 :(得分:1)

NSString不代表任何样式信息。只有NSString表示,无法知道该字符串是否应该以粗体,斜体,72磅或漫画Sans显示。

此样式信息(“属性”)在NSAttributedString中表示。

NSString *myString = @"Hello world!";
NSAttributedString *myBoldString = [[NSAttributedString alloc] initWithString:myString
                                                             attributes:@{ NSFontAttributeName: [UIFont boldSystemFontOfSize:72.0] }];

这将创建一个包含样式信息的字符串。例如,如果您想在UILabel上显示此字符串,则需要设置.attributedText属性而不是.text

self.label.attributedText = myBoldString;

数据(字符串内容)与表示(样式属性)的分离是Cocoa和Cocoa Touch中的常见主题。