iphone/ipad:究竟如何使用 NSAttributedString? [英] iphone/ipad: How exactly use NSAttributedString?
问题描述
是的,很多人都在谈论 iPhone/iPad 中的富文本,很多人都知道 NSAttributedString
.
Yes, many people are saying about Rich Text in iPhone/iPad and many knows about NSAttributedString
.
但是如何使用NSAttributedString
?我搜索了很多时间,没有提取线索.
But how to use NSAttributedString
? I searched for much time, no extract clues for this.
我知道如何设置NSAttributedString
,那么我应该怎么做才能在iPhone/iPad上显示富文本的文本?
I know how to set up a NSAttributedString
, then what should I do to display a text on iPhone/iPad with rich text?
官方文档说它应该与CoreText.Framework
一起使用,这是什么意思?
The official docs says it should be used with CoreText.Framework
, what does that mean?
有没有这样简单的方法?
Is there any simple way like this?
NSAttributedString *str;
.....
UILabel *label;
label.attributedString = str;
推荐答案
You should take a look at AliSoftware's OHAttributedLabel. It is a subclass of UILabel that draws an NSAttributedString and also provides convenience methods for setting the attributes of an NSAttributedString from UIKit classes.
来自 repo 中提供的示例:
From the sample provided in the repo:
#import "NSAttributedString+Attributes.h"
#import "OHAttributedLabel.h"
/**(1)** Build the NSAttributedString *******/
NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString:@"Hello World!"];
// for those calls we don't specify a range so it affects the whole string
[attrStr setFont:[UIFont systemFontOfSize:12]];
[attrStr setTextColor:[UIColor grayColor]];
// now we only change the color of "Hello"
[attrStr setTextColor:[UIColor redColor] range:NSMakeRange(0,5)];
/**(2)** Affect the NSAttributedString to the OHAttributedLabel *******/
myAttributedLabel.attributedText = attrStr;
// Use the "Justified" alignment
myAttributedLabel.textAlignment = UITextAlignmentJustify;
// "Hello World!" will be displayed in the label, justified, "Hello" in red and " World!" in gray.
注意:在 iOS 6+ 中,您可以使用 attributedText UILabel 的属性.
Note: In iOS 6+ you can render attributed strings using the attributedText property of UILabel.
这篇关于iphone/ipad:究竟如何使用 NSAttributedString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!