在Three20中,有TTStyledTextLabel类,它相当于一个在IE中显示一段HTML的显示窗口,它的实现由两个部分来组成:
1.创建TTStyledTextLabel对象,并且将它增加到当前的View中。如下图及代码。
NSString* kText =@"\
This is a test of styled labels. Styled labels support \
<b>bold text</b>, <i>italic text</i>, <span class=\"blueText\">colored text</span>, \
<span class=\"largeText\">font sizes</span>, \
<span class=\"blueBox\">spans with backgrounds</span>, inline images \
<img src=\"bundle://smiley.png\"/>, and <a href=\"http://www.google.com\">hyperlinks</a> you can \
actually touch. URLs are automatically converted into links, like this: http://www.ccwit.com\
<div>You can enclose blocks within an HTML div.</div>\
Both line break characters\n\nand HTML line breaks<br/>are respected.";
TTStyledTextLabel* label1 = [[[TTStyledTextLabelalloc]initWithFrame:self.view.bounds]autorelease];
label1.font = [UIFontsystemFontOfSize:17];
label1.text = [TTStyledTexttextFromXHTML:kText
lineBreaks:YESURLs:YES];
label1.contentInset =UIEdgeInsetsMake(10,10,
10, 10);
[label1 sizeToFit];
[self.viewaddSubview:label1];
2.label1对象中的显示text是通过style来进行控制的,也可以通过类来提供,如下:
@interface TextTestStyleSheet :TTDefaultStyleSheet
@end
@implementation TextTestStyleSheet
- (TTStyle*)blueText {
return [TTTextStylestyleWithColor:[UIColorblueColor]
next:nil];
}
- (TTStyle*)largeText {
return [TTTextStylestyleWithFont:[UIFontsystemFontOfSize:32]next:nil];
}
- (TTStyle*)smallText {
return [TTTextStylestyleWithFont:[UIFontsystemFontOfSize:12]next:nil];
}
- (TTStyle*)floated {
return [TTBoxStylestyleWithMargin:UIEdgeInsetsMake(0,0,
5,5)
padding:UIEdgeInsetsMake(0,0,
0, 0)
minSize:CGSizeZeroposition:TTPositionFloatLeftnext:nil];
}
- (TTStyle*)blueBox {
return
[TTShapeStyle
styleWithShape:[TTRoundedRectangleShapeshapeWithRadius:6]next:
[TTInsetStylestyleWithInset:UIEdgeInsetsMake(0,
-5, -4, -6)
next:
[TTShadowStylestyleWithColor:[UIColorgrayColor]
blur:2offset:CGSizeMake(1,1)next:
[TTSolidFillStylestyleWithColor:[UIColorpurpleColor]
next:
[TTSolidBorderStylestyleWithColor:[UIColorgrayColor]
width:1next:nil]]]]];
}
- (TTStyle*)inlineBox {
return
[TTSolidFillStylestyleWithColor:[UIColorblueColor]
next:
[TTBoxStylestyleWithPadding:UIEdgeInsetsMake(5,13,5,13)next:
[TTSolidBorderStylestyleWithColor:[UIColorblackColor]
width:1next:nil]]];
}
- (TTStyle*)inlineBox2 {
return
[TTSolidFillStylestyleWithColor:[UIColorcyanColor]
next:
[TTBoxStylestyleWithMargin:UIEdgeInsetsMake(5,50,0,50)
padding:UIEdgeInsetsMake(0,13,0,13)next:nil]];
}
@end
最后,别忘在在label1对象有效之前,调用
[TTStyleSheetsetGlobalStyleSheet:[[[TextTestStyleSheetalloc]
init]autorelease]];
使label显示时使用TextTestStyleSheet提供的风格来显示。如下图所示的效果: