67

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

汤姆:一些信息。

就像在 Facebook 应用程序中显示“你在想什么?”的方式一样。消息。有没有人有任何建议如何解决这个问题?

4

10 回答 10

103

有一种方法可以使用 NSMutableAttributedString 在标签上设置不同/多种字体和其他属性。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,作为文件所有者的出口。人们可以继续附加他想要的尽可能多的 NSMutableAttributedString ..

另请注意,我在我的项目中添加了 verdana 和 arial 字体并为此添加了 plist。

于 2013-02-05T16:31:39.590 回答
27

对不起,迟到的答案。下面的代码对我很有用。我发布这个是为了对某人有所帮助。

    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;

在此处输入图像描述

请注意,My 是半粗体,profile 是常规的。我使用了 MyRiad 字体。谢谢

于 2014-10-30T11:33:30.220 回答
18

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

或者,您可以继承 UILabel,并在 drawRect 中自己绘制文本。如果您这样做,只需添加一个实例变量来告诉您要以一种格式绘制多少字符串,然后以另一种格式绘制其余部分。

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

于 2009-09-13T10:11:54.010 回答
18

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

我创建了这个基本的 UIView 子类来支持类似的功能。

它不支持的列表比它支持的要长,但基本上它允许您管理单行UILabel 并根据需要设置每个 UILabel 的格式。例如,这让我可以在行中间插入不同颜色的文本,并避免使用重量级的 UIWebView。

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

//  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
于 2009-10-07T16:14:02.013 回答
16

在 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

编辑
Swift 4.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:
    NSAttributedString.Key.font as NSCopying)
let boldDict:NSDictionary = NSDictionary(object: boldFont, forKey:
    NSAttributedString.Key.font as NSCopying)
let thirdDict:NSDictionary = NSDictionary(object: thirdFont, forKey:
    NSAttributedString.Key.font as NSCopying)

let firstText = "My name is "
let attributedString = NSMutableAttributedString(string: firstText,
                                                         attributes: firstDict as? [NSAttributedString.Key : Any])

let boldText  = "Rajan"
let boldString = NSMutableAttributedString(string:boldText,
                                                   attributes:boldDict as? [NSAttributedString.Key : Any])

let finalText = " iOS"
let finalAttributedString =  NSMutableAttributedString(string:
    finalText, attributes: thirdDict as? [NSAttributedString.Key : Any])

attributedString.append(boldString)
attributedString.append(finalAttributedString)
myLabel.attributedText = attributedString

这看起来像

在此处输入图像描述

于 2015-10-11T19:00:13.130 回答
7

我更新了 @Jason 建议的 MultipartLabel,添加了 contentMode(文本对齐)支持。

多部分标签.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

多部分标签.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
于 2011-09-06T07:00:26.567 回答
1

使用 CoreText API 会快很多。

这里有几个例子

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

文本绘制逻辑: - 您将需要知道“名称”的范围,因此如果Tom:一些消息。是您的字符串,您必须为范围 (0, 3) 应用不同的字体。

您可以使用 CoreText 自定义所有内容 :)

于 2012-08-08T08:12:16.650 回答
0

嗨 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];
于 2014-04-11T08:52:26.153 回答
-5

一种选择是使用 UIWebView 而不是 UILabel。

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

于 2011-07-08T05:57:32.827 回答
-6

构建自己的 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]; 
于 2011-08-24T16:45:16.860 回答