2011-05-16 63 views
2

的的UILabel我願做這樣的事情在iPhone上用一個UILabel:iPhone:長度可變,多行字符串與多種字體

李四,李四,約翰·史密斯,
簡·史密斯
喜歡這張照片。

我可以畫我自己的文字,並讓它實現多種字體在同一條線上,就像在question here,但一旦它跨越多行,這種類型的解決並沒有真正似乎工作,因爲sizeWithFont:forWidth:lineBreakMode:方法返回一個CGRect,和我想像,要麼做這樣的事情:

李四,李四,約翰·史密斯,珍妮·史密斯喜歡這張照片。

或者這樣:

李四,李四,約翰·史密斯,
簡·史密斯

喜歡這張照片。

但是,我想繼續第二個字體,第一個字體離開,並在同一行。有什麼辦法可以讓iPhone在iPhone上發生嗎?

+0

如果使用three20庫是一個選項,那麼你可以使用[three20](http://www.three20.info)TTStyledText的textFromXHTML函數。示例用法可以在TTCatalog項目中找到。這裏是[TTStyledText]的文檔(http://api.three20.info/interface_t_t_styled_text.php) – 2011-05-16 09:04:55

+0

它可能對你更有用** UITextView對象**(將其設置爲**不可編輯**,您將從中獲得與UILabel非常接近的行爲,並具有更大的靈活性)。 – 2011-05-16 09:11:32

回答

1

我已經使用核心文本來處理這些文本,以在某些地方顯示不同的字體。核心文本爲您提供了更改字體,大小和設置段落屬性的靈活性。關於核心文本的詳細信息可以在這裏找到http://developer.apple.com/library/ios/#documentation/StringsTextFonts/Conceptual/CoreText_Programming/Introduction/Introduction.html

給你的是如何做的一個例子:

-(void) drawLayer:(CALayer *)layerToDraw inContext:(CGContextRef)context { 
NSMutableAttributedString* someString = [[NSMutableAttributedString alloc] initWithString:@"New String"]; 
CTFontRef font = CTFontCreateWithName(@"Arial", 25, NULL); 
[someString addAttribute:(id)kCTFontAttributeName value:(id)font range:NSMakeRange(0, 3)]; 
CFRelease(font); 

CGMutablePathRef path = CGPathCreateMutable(); 
CGPathAddRect(path, NULL, labelLayer.bounds); 

CGContextSetTextMatrix(context, CGAffineTransformIdentity); 
CGContextTranslateCTM(context, 0, labelLayer.bounds.size.height); 
CGContextScaleCTM(context, 1.0, -1.0); 

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(someString); 
CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL); 

CTFrameDraw(frame, context); 


CFRelease(framesetter); 
CFRelease(frame); 
CFRelease(path); 
} 

但是,如果這種用法是在你的項目非常少,你可以只使用一個UIWebView展示這樣的文本(請記住,這會消耗更多的資源)

1

有一種方法可以使用NSMutableAttributedString在Label上設置不同/多個字體&。 FOLL是我的代碼:

UIFont *ArialFont = [UIFont fontWithName:@"arial" size:18.0]; 
NSDictionary *arialdict = [NSDictionary dictionaryWithObject: ArialFont forKey:NSFontAttributeName];  
NSMutableAttributedString *AattrString = [[NSMutableAttributedString alloc] initWithString:title attributes: arialdict]; 

UIFont *VerdanaFont = [UIFont fontWithName:@"verdana" size:12.0]; 
NSDictionary *veradnadict = [NSDictionary dictionaryWithObject:VerdanaFont forKey:NSFontAttributeName]; 
NSMutableAttributedString *VattrString = [[NSMutableAttributedString alloc]initWithString: newsDate attributes:veradnadict];  
[VattrString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:(NSMakeRange(0, 15))]; 

[AattrString appendAttributedString:VattrString]; 


lblText.attributedText = AattrString; 

注意lblText是的UILabel,插座,因爲文件的所有者。 人們可以繼續追加許多NSMutableAttributedString他想..

還要注意,我已經添加了宋體& Arial字體在我的項目&添加一個相同的plist中。