出现的问题
我们希望在UI组件中使用的文字有丰富多彩的样式,但是我们不希望为了丰富样式而将每一个文字都分割开来分别定义样式,更不希望先将文字图片话处理,然后加入到组件中,这样会占用更多的内存空间,对于iPhone等移动设备来说,这样做不科学,也不合理!比如说要按如下样式显示一个字符串。
多样式的字符串显示
如何解决问题
其实这个问题在OS X的系统中早已经解决掉了,针对一个NSString对象,我们可以为其中的文字定义不同的样式。但在iOS系统中,直到iOS 6才出现这个功能,所以使用这个功能时必须要考虑到系统的兼容性,如果希望兼容iOS 6之前的系统就得要重新考虑了。
具体做法就是使用NSAttributedString对象将普通的NSString对象属性话,当然这个对象是不可变的,其对应的可变对象是NSMutableAttributedString。
NSAttributedString对象可以通过initWithString:方法进行初始化,由于这个对象不可变,所以我们为了能更好的定义样式,通常使用其可变对象NSMutableString,初始化方法可能initWithString:是在NSAttributedString (NSExtendedAttributedString)中定义的。
然后可以通过创建属性字典NSDictionary,来定义属性,并用NSMutableAttributedString对象的- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;方法来为传入的NSString对象中的不同文字定义不同的样式。
如何创建属性字典
上面说了,我们需要定义一个属性的字典为不同的样式。这个可以通过API文档查询NSAttributedString看到有哪些属性是可以定义的。这里就说说上面效果需要用到的几个属性:
NSFontAttributeName:通过传入一个UIFont对象来定义文字的字体;
NSForegroundColorAttributeName:通过传入一个UIColor对象来定义文字的颜色;
NSBackgroundColorAttributeName:通过传入一个UIColor对象来定义文字的背景颜色;
NSShadowAttributeName:通过传入一个NSShadow来定义文字的阴影。
实现程序
下面代码就是上面效果的实现,通过定义一个label,然后设置其内容为一个带样式的文字对象即可。
#import "ViewController.h" |
@interface ViewController () |
@property (nonatomic, strong) UILabel * label; |
- (NSAttributedString *)attributedText; |
@implementation ViewController |
self.label = [[UILabel alloc] init]; |
self.label.backgroundColor = [UIColor clearColor]; |
self.label.attributedText = [self attributedText]; |
self.label.center = self.view.center; |
[self.view addSubview:self.label]; |
- ( void )didReceiveMemoryWarning |
[super didReceiveMemoryWarning]; |
- (NSAttributedString *)attributedText { |
NSString * string = @ "XCoder Studio" ; |
NSMutableAttributedString * result = [[NSMutableAttributedString alloc] initWithString:string]; |
NSDictionary * attributesForFirstWord = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:40.0f], |
NSForegroundColorAttributeName: [UIColor redColor], |
NSBackgroundColorAttributeName: [UIColor blackColor]}; |
NSShadow * shadow = [[NSShadow alloc] init]; |
shadow.shadowColor = [UIColor darkGrayColor]; |
shadow.shadowOffset = CGSizeMake(4.0f, 4.0f); |
NSDictionary * attributesForSecondWord = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:40.0f], |
NSForegroundColorAttributeName: [UIColor whiteColor], |
NSBackgroundColorAttributeName: [UIColor redColor], |
NSShadowAttributeName: shadow}; |
[result setAttributes:attributesForFirstWord range:[string rangeOfString:@ "XCoder" ]]; |
[result setAttributes:attributesForSecondWord range:[string rangeOfString:@ "Studio" ]]; |
return [[NSAttributedString alloc] initWithAttributedString:result]; |
编译完成后就可以得到上述效果了!
转载:http://www.xcoder.cn/index.php/archives/667