iPhone – 同时包含多种字体的文本的UILabel

我正在寻找一种方式来使用UILabel(或类似的东西)来显示这样的东西:

汤姆:一些消息。

这就像是如何在Facebook应用程序中完成显示“你在想什么? 消息。 有没有人有任何build议如何处理这个?

根据需要使用两个UILabel IBOutlet,每个都有不同的格式(字体/颜色/等)。根据第一个文本的结束位置移动第二个UOabel IBOutlet。 你可以通过sizeWithFont获取:forWidth:lineBreakMode:

或者,您可以inheritanceUILabel,并在drawRect中自己绘制文本。 如果你这样做,只要添加一个实例variables来告诉你多lessstring以一种格式绘制,并在其他绘制剩余的。

更新:请参阅下面的@ Akshay的回复。 从iOS6开始,UILabel的可以包含NSMutableAttributedString。 当我写这个,这是不可用的。

有一种方法可以使用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 *verdanaDict = [NSDictionary dictionaryWithObject:VerdanaFont forKey:NSFontAttributeName]; NSMutableAttributedString *vAttrString = [[NSMutableAttributedString alloc]initWithString: newsDate attributes:verdanaDict]; [vAttrString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:(NSMakeRange(0, 15))]; [aAttrString appendAttributedString:vAttrString]; lblText.attributedText = aAttrString; 

请注意,lblText是作为文件所有者的UILabel,outlet。 你可以继续追加他想要的NSMutableAttributedString。

另外请注意,我已经在我的项目中添加了verdana&arial字体,并添加了一个plist。

对不起,迟到的答案。 下面的代码对我很好。 我张贴这个,这样可以帮助某人。

  UIFont *font1 = [UIFont fontWithName:kMyriadProSemiBold size:15]; NSDictionary *arialDict = [NSDictionary dictionaryWithObject: font1 forKey:NSFontAttributeName]; NSMutableAttributedString *aAttrString1 = [[NSMutableAttributedString alloc] initWithString:@"My" attributes: arialDict]; UIFont *font2 = [UIFont fontWithName:kMyriadProRegular size:15]; NSDictionary *arialDict2 = [NSDictionary dictionaryWithObject: font2 forKey:NSFontAttributeName]; NSMutableAttributedString *aAttrString2 = [[NSMutableAttributedString alloc] initWithString:@"Profile" attributes: arialDict2]; [aAttrString1 appendAttributedString:aAttrString2]; myProfileLabel.attributedText = aAttrString1; 

在这里输入图像描述

请注意我的是semibold和configuration文件是正常的。 我使用了MyRiad字体。 谢谢

更新:如果你是iOS 6+,那么使用UILabel.attributedText – 否则….

我创build了这个基本的UIView子类来支持类似的function。

支持的东西比它所做的更长,但基本上它可以让你pipe理一行UILabel,并根据你的需要进行格式化。 这可以让我插入不同颜色的文本在行中,例如,并避免使用重量级的UIWebView。

我通过在我的界面(使用Interface Builder)中放置一个UIView对象并将IB中的对象的types设置为MultipartLabel来创build这些对象。 然后在代码中,根据需要调用updateNumberOfLabels和各种setTextselect器。

 // MultipartLabel.m // MultiLabelLabel // // Created by Jason Miller on 10/7/09. // Copyright 2009 Jason Miller. All rights reserved. // #import "MultipartLabel.h" @interface MultipartLabel (Private) - (void)updateLayout; @end @implementation MultipartLabel @synthesize containerView; @synthesize labels; -(void)updateNumberOfLabels:(int)numLabels; { [containerView removeFromSuperview]; self.containerView = nil; self.containerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)] autorelease]; [self addSubview:self.containerView]; self.labels = [NSMutableArray array]; while (numLabels-- > 0) { UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero]; [self.containerView addSubview:label]; [self.labels addObject:label]; [label release]; } [self updateLayout]; } -(void)setText:(NSString *)text forLabel:(int)labelNum; { if( [self.labels count] > labelNum && labelNum >= 0 ) { UILabel * thisLabel = [self.labels objectAtIndex:labelNum]; thisLabel.text = text; } [self updateLayout]; } -(void)setText:(NSString *)text andFont:(UIFont*)font forLabel:(int)labelNum; { if( [self.labels count] > labelNum && labelNum >= 0 ) { UILabel * thisLabel = [self.labels objectAtIndex:labelNum]; thisLabel.text = text; thisLabel.font = font; } [self updateLayout]; } -(void)setText:(NSString *)text andColor:(UIColor*)color forLabel:(int)labelNum; { if( [self.labels count] > labelNum && labelNum >= 0 ) { UILabel * thisLabel = [self.labels objectAtIndex:labelNum]; thisLabel.text = text; thisLabel.textColor = color; } [self updateLayout]; } -(void)setText:(NSString *)text andFont:(UIFont*)font andColor:(UIColor*)color forLabel:(int)labelNum; { if( [self.labels count] > labelNum && labelNum >= 0 ) { UILabel * thisLabel = [self.labels objectAtIndex:labelNum]; thisLabel.text = text; thisLabel.font = font; thisLabel.textColor = color; } [self updateLayout]; } - (void)updateLayout { int thisX = 0; // TODO when it is time to support different sized fonts, need to adjust each y value to line up baselines for (UILabel * thisLabel in self.labels) { CGSize size = [thisLabel.text sizeWithFont:thisLabel.font constrainedToSize:CGSizeMake(9999, 9999) lineBreakMode:thisLabel.lineBreakMode]; CGRect thisFrame = CGRectMake( thisX, 0, size.width, size.height ); thisLabel.frame = thisFrame; thisX += size.width; } } - (void)dealloc { [labels release]; labels = nil; [containerView release]; containerView = nil; [super dealloc]; } @end 

在swift 2.0中可以这样做,如下所示

 //Defining fonts of size and type let firstfont:UIFont = UIFont(name: "Helvetica Neue", size: 17)! let boldFont:UIFont = UIFont(name: "HelveticaNeue-Bold", size: 17)! let thirdFont:UIFont = UIFont(name: "HelveticaNeue-ThinItalic", size: 17)! //Making dictionaries of fonts that will be passed as an attribute let firstDict:NSDictionary = NSDictionary(object: firstfont, forKey: NSFontAttributeName) let boldDict:NSDictionary = NSDictionary(object: boldFont, forKey: NSFontAttributeName) let thirdDict:NSDictionary = NSDictionary(object: thirdFont, forKey: NSFontAttributeName) let firstText = "My name is " let attributedString = NSMutableAttributedString(string: firstText, attributes: firstDict as? [String : AnyObject]) let boldText = "Rajan" let boldString = NSMutableAttributedString(string:boldText, attributes:boldDict as? [String : AnyObject]) let finalText = " iOS" let finalAttributedString = NSMutableAttributedString(string: finalText, attributes: thirdDict as? [String : AnyObject]) attributedString.appendAttributedString(boldString) attributedString.appendAttributedString(finalAttributedString) myLabel.attributedText = attributedString 

编辑
Swift 3.0

 let firstfont:UIFont = UIFont(name: "Helvetica Neue", size: 17)! let boldFont:UIFont = UIFont(name: "HelveticaNeue-Bold", size: 17)! let thirdFont:UIFont = UIFont(name: "HelveticaNeue-ThinItalic", size: 17)! //Making dictionaries of fonts that will be passed as an attribute let firstDict:NSDictionary = NSDictionary(object: firstfont, forKey: NSFontAttributeName as NSCopying) let boldDict:NSDictionary = NSDictionary(object: boldFont, forKey: NSFontAttributeName as NSCopying) let thirdDict:NSDictionary = NSDictionary(object: thirdFont, forKey: NSFontAttributeName as NSCopying) let firstText = "My name is " let attributedString = NSMutableAttributedString(string: firstText, attributes: firstDict as? [String : AnyObject]) let boldText = "Rajan" let boldString = NSMutableAttributedString(string:boldText, attributes:boldDict as? [String : AnyObject]) let finalText = " iOS" let finalAttributedString = NSMutableAttributedString(string: finalText, attributes: thirdDict as? [String : AnyObject]) attributedString.append(boldString) attributedString.append(finalAttributedString) myLabel.attributedText = attributedString 

这看起来像

在这里输入图像描述

我更新了@Jasonbuild议的MultipartLabel,添加contentMode(文本alignment)支持。

MultipartLabel.h

 #import <Foundation/Foundation.h> @interface MultipartLabel : UIView { } @property (nonatomic,retain) UIView *containerView; @property (nonatomic,retain) NSMutableArray *labels; @property (nonatomic) UIViewContentMode contentMode; - (void)updateNumberOfLabels:(int)numLabels; - (void)setText:(NSString *)text forLabel:(int)labelNum; - (void)setText:(NSString *)text andFont:(UIFont*)font forLabel:(int)labelNum; - (void)setText:(NSString *)text andColor:(UIColor*)color forLabel:(int)labelNum; - (void)setText:(NSString *)text andFont:(UIFont*)font andColor:(UIColor*)color forLabel:(int)labelNum; @end 

MultipartLabel.m

 // MultipartLabel.m // MultipartLabel // // Created by Jason Miller on 10/7/09. // Updated by Laurynas Butkus, 2011 // Copyright 2009 Jason Miller. All rights reserved. // #import "MultipartLabel.h" @interface MultipartLabel (Private) - (void)updateLayout; @end @implementation MultipartLabel @synthesize containerView; @synthesize labels; @synthesize contentMode; -(void)updateNumberOfLabels:(int)numLabels { [containerView removeFromSuperview]; self.containerView = nil; self.containerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)] autorelease]; [self addSubview:self.containerView]; self.labels = [NSMutableArray array]; while (numLabels-- > 0) { UILabel * label = [[UILabel alloc] initWithFrame:CGRectZero]; label.backgroundColor = self.backgroundColor; [self.containerView addSubview:label]; [self.labels addObject:label]; [label release]; } [self updateLayout]; } -(void)setText:(NSString *)text forLabel:(int)labelNum { if( [self.labels count] > labelNum && labelNum >= 0 ) { UILabel * thisLabel = [self.labels objectAtIndex:labelNum]; thisLabel.text = text; } [self updateLayout]; } -(void)setText:(NSString *)text andFont:(UIFont*)font forLabel:(int)labelNum { if( [self.labels count] > labelNum && labelNum >= 0 ) { UILabel * thisLabel = [self.labels objectAtIndex:labelNum]; thisLabel.text = text; thisLabel.font = font; } [self updateLayout]; } -(void)setText:(NSString *)text andColor:(UIColor*)color forLabel:(int)labelNum { if( [self.labels count] > labelNum && labelNum >= 0 ) { UILabel * thisLabel = [self.labels objectAtIndex:labelNum]; thisLabel.text = text; thisLabel.textColor = color; } [self updateLayout]; } - (void)setText:(NSString *)text andFont:(UIFont*)font andColor:(UIColor*)color forLabel:(int)labelNum { if( [self.labels count] > labelNum && labelNum >= 0 ) { UILabel * thisLabel = [self.labels objectAtIndex:labelNum]; thisLabel.text = text; thisLabel.font = font; thisLabel.textColor = color; } [self updateLayout]; } - (void)updateLayout { int thisX; int thisY; int totalWidth = 0; int offsetX = 0; int sizes[[self.labels count]][2]; int i = 0; for (UILabel * thisLabel in self.labels) { CGSize size = [thisLabel.text sizeWithFont:thisLabel.font constrainedToSize:CGSizeMake(9999, 9999) lineBreakMode:thisLabel.lineBreakMode]; sizes[i][0] = size.width; sizes[i][1] = size.height; totalWidth+= size.width; i++; } i = 0; for (UILabel * thisLabel in self.labels) { // X switch (self.contentMode) { case UIViewContentModeRight: case UIViewContentModeBottomRight: case UIViewContentModeTopRight: thisX = self.frame.size.width - totalWidth + offsetX; break; case UIViewContentModeCenter: thisX = (self.frame.size.width - totalWidth) / 2 + offsetX; break; default: thisX = offsetX; break; } // Y switch (self.contentMode) { case UIViewContentModeBottom: case UIViewContentModeBottomLeft: case UIViewContentModeBottomRight: thisY = self.frame.size.height - sizes[i][1]; break; case UIViewContentModeCenter: thisY = (self.frame.size.height - sizes[i][1]) / 2; break; default: thisY = 0; break; } thisLabel.frame = CGRectMake( thisX, thisY, sizes[i][0], sizes[i][1] ); offsetX += sizes[i][0]; i++; } } - (void)dealloc { [labels release]; labels = nil; [containerView release]; containerView = nil; [super dealloc]; } @end 

使用CoreText API会更快。

这里有几个例子

基本上你需要做的事情是:1:创buildUIView子类2:在drawRect:方法中添加文本绘制逻辑。

文本绘制逻辑: – 您将需要知道“名称”的范围,所以如果汤姆 :一些消息。 是你的string,你将不得不为范围应用不同的字体(0,3)。

你可以用CoreText自定义一切:)

嗨OHAttributelabel是这个好方法。你可以参考下面的示例代码链接https://github.com/AliSoftware/OHAttributedLabel从它导入OHAttribute框架,你可以设置你的标签如下;

  OHAttributedLabel *lblText; lblText = [[OHAttributedLabel alloc] initWithFrame:CGRectMake(10,10,100,19)]; lblText.backgroundColor = [UIColor clearColor]; lblText.textAlignment = UITextAlignmentCenter; lblText.font = [UIFont fontWithName:@"BoschSans-Regular" size:10]; NSString *strText=@"Tom: Some message."; NSMutableAttributedString* attrStr = [NSMutableAttributedString attributedStringWithString: strText]; NSRange rangeOfSubstring = [strVersion rangeOfString:@“Tom:]; if (rangeOfSubstring.location != NSNotFound) { [attrStr setFontName:@"BoschSans-BOLD" size:10.0 range:rangeOfSubstring]; } else { } lblText.attributedText = attrStr; [self.View addSubview: lblText]; 

一个select是使用UIWebView而不是UILabel。

一个例子: http : //iphoneincubator.com/blog/windows-views/display-rich-text-using-a-uiwebview

build立自己的HTML代码非常容易=>

 UIWebView *titleAd = [UIWebView alloc] init...; NSString *cssString = [NSString stringWithFormat:@".title {font-family: HelveticaNeue; text-decoration: bold; font-size: %fpt; color: #4083a9;} .author {font-family: HelveticaNeue; text-decoration: bold; font-size: %fpt; color: #3e4545;}",__FONTSIZE_29__, __FONTSIZE_21__]; NSString *htmlString = [NSString stringWithFormat:@"<html> <head> <style type=\"text/css\"> %@ </style> </head> <body> <p> <span class=\"title\"> %@ </span> <span class=\"author\"> proposé par %@ </span> </p> </body> </html>", cssString, [table title], [table nameOwner]]; [titleAd loadHTMLString:htmlString baseURL:nil];