首页 > 代码库 > label显示不同的字体颜色

label显示不同的字体颜色

问题描述:在一个控件label中,添加两种不同颜色和字体的文字,并且加上点击事件

直接上代码:

需要加上CoreText库文件

//

//  MutableLabel.h

//  MyLabelDemo

//

//  Created by xwg on 14-7-15.

//  Copyright (c) 2014年 希望谷. All rights reserved.

//

 

#import <UIKit/UIKit.h>

 

@interface MutableLabel : UILabel

{

    NSMutableAttributedString *attributedString;

    UIControl *_textActionView;

    UIControl *_titleActionView;

    UIControl *_mutableLineActionView;

    UIColor *_hightlightedColor;

    NSString *_ktext;

    NSString *_ktitle;

    UIFont *_textFont;

}

/*

    说明:先设置text再设置title

 */

 

@property(nonatomic, assign)NSUInteger nameTag;

@property(nonatomic, assign)NSUInteger textTag;

 

//为内容添加文字

 

-(void)setTitle:(NSString *)title withFont:(UIFont *)titleFont titleColor:(UIColor *)titleColor andText:(NSString *)text andTextFont:(UIFont *)textFont andTextColor:(UIColor *)textColor;

 

-(void)setText:(NSString *)text withFont:(UIFont *)font andColor:(UIColor *)color;

 

//为姓名添加文字

-(void)setTitle:(NSString *)title withFont:(UIFont *)font andColor:(UIColor *)color;

 

//为内容添加点击事件

-(void)addTargetToText:(id)target action:(SEL)action;

 

//为姓名添加点击事件

-(void)addTargetToTitle:(id)target action:(SEL)action;

 

@end

 

 

实现文件

//

//  MutableLabel.m

//  MyLabelDemo

//

//  Created by xwg on 14-7-15.

//  Copyright (c) 2014年 希望谷. All rights reserved.

//

 

#import "MutableLabel.h"

#import <CoreText/CoreText.h>

 

@implementation MutableLabel

 

- (instancetype)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self)

    {

        attributedString = [[NSMutableAttributedString alloc]init];

    }

    return self;

}

 

-(void)setTitle:(NSString *)title withFont:(UIFont *)titleFont titleColor:(UIColor *)titleColor andText:(NSString *)text andTextFont:(UIFont *)textFont andTextColor:(UIColor *)textColor

{

    self.text = [NSString stringWithFormat:@"%@: %@",title,text];

    _ktext = [text copy];

    _textFont = [textFont retain];

    NSUInteger len = [self.text length];

    NSRange textRange = NSMakeRange(0, len);

    

    //带有属性的字符串

    NSMutableAttributedString *mutaString = [[NSMutableAttributedString alloc]initWithString:self.text];

    [mutaString addAttribute:(NSString *)(kCTForegroundColorAttributeName) value:(id)textColor.CGColor range:textRange];//添加字体颜色属性

    CTFontRef ctfont = CTFontCreateWithName((__bridge CFStringRef)textFont.fontName, textFont.pointSize, NULL);

    [mutaString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)ctfont range:textRange];

    CFRelease(ctfont);

    

    _ktitle = [title copy];

    NSUInteger len1 = [title length]+1;

    NSRange titleRang = NSMakeRange(0, len1);

    

    [mutaString addAttribute:NSForegroundColorAttributeName value:titleColor range:titleRang];

    [mutaString addAttribute:NSFontAttributeName value:titleFont range:titleRang];

     attributedString = mutaString;

    

    NSMutableParagraphStyle *ps = [[NSMutableParagraphStyle alloc] init];

    [ps setLineBreakMode:NSLineBreakByCharWrapping];

    [attributedString addAttribute:NSParagraphStyleAttributeName value:ps range:textRange];

    [ps release];

}

 

-(void)setText:(NSString *)text withFont:(UIFont *)font andColor:(UIColor *)color

{

    self.text = text;

    _ktext = [text copy];

    _textFont = [font retain];

    NSUInteger len = [text length];

    NSRange textRange = NSMakeRange(0, len);

    

    //带有属性的字符串

    NSMutableAttributedString *mutaString = [[NSMutableAttributedString alloc]initWithString:text];

    [mutaString addAttribute:(NSString *)(kCTForegroundColorAttributeName) value:(id)color.CGColor range:textRange];//添加字体颜色属性

    CTFontRef ctfont = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);

    [mutaString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)ctfont range:textRange];

    CFRelease(ctfont);

    attributedString = mutaString;

   

 

   }

 

-(void)setTitle:(NSString *)title withFont:(UIFont *)font andColor:(UIColor *)color

{

    _ktitle = [title copy];

    NSString *text = [NSString stringWithFormat:@"%@%@",title,self.text];

    self.text = text;

    

    NSUInteger len = [title length];

    NSRange titleRang = NSMakeRange(0, len);

    NSMutableAttributedString *titleString = [[NSMutableAttributedString alloc]initWithString:title];

    [attributedString insertAttributedString:titleString atIndex:0];

     [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:titleRang];

//    [titleString addAttribute:(NSString *)(kCTForegroundColorAttributeName) value:(id)color.CGColor range:titleRang];

//    

//    CTFontRef ctfont = CTFontCreateWithName((__bridge CFStringRef)font.fontName, font.pointSize, NULL);

//    [titleString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)ctfont range:titleRang];

//    CFRelease(ctfont);

//    [attributedString insertAttributedString:titleString atIndex:0];

    [titleString release];

 

    //添加点击事件

    [self setUserInteractionEnabled:YES];

    NSDictionary *attributeDict = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];

    CGSize titleSize = [_ktitle sizeWithAttributes:attributeDict];

    _titleActionView = [[UIControl alloc]initWithFrame:CGRectMake(0, 0, titleSize.width, titleSize.height)];

    [_titleActionView setBackgroundColor:[UIColor clearColor]];

    [self addSubview:_titleActionView];

    [self sendSubviewToBack:_titleActionView];

    

    

    

    NSDictionary *attributeDict1 = [NSDictionary dictionaryWithObjectsAndKeys:_textFont,NSFontAttributeName, nil];

    CGSize textSize = [_ktext sizeWithAttributes:attributeDict1];

    

    _textActionView = [[UIControl alloc]initWithFrame:CGRectMake(textSize.width, 0, self.bounds.size.width - textSize.width, textSize.height)];

    [_textActionView setBackgroundColor:[UIColor clearColor]];

    [self addSubview:_textActionView];

    [self sendSubviewToBack:_textActionView];

    

    if(titleSize.width+textSize.width > self.bounds.size.width)

    {

        //折行

        _mutableLineActionView = [[UIControl alloc]initWithFrame:CGRectMake(0, titleSize.height, self.bounds.size.width, self.bounds.size.height-titleSize.height)];

        [_mutableLineActionView setBackgroundColor:[UIColor clearColor]];

        [self addSubview:_mutableLineActionView];

        [self sendSubviewToBack:_mutableLineActionView];

        

    }

}

 

-(void)addTargetToText:(id)target action:(SEL)action

{

    [_textActionView addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    if(_mutableLineActionView != nil)

    {

        [_mutableLineActionView addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    }

}

 

-(void)addTargetToTitle:(id)target action:(SEL)action

{

    [_titleActionView addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

}

 

-(void)drawRect:(CGRect)rect

{

    if (self.text !=nil)

    {

        CGContextRef context = UIGraphicsGetCurrentContext();

        CGContextSaveGState(context);

        CGContextTranslateCTM(context, 0.0, 0.0);//move

        CGContextScaleCTM(context, 1.0, -1.0);

        CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge  CFAttributedStringRef)attributedString);

        CGMutablePathRef pathRef = http://www.mamicode.com/CGPathCreateMutable();

        CGPathAddRect(pathRef,NULL , CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height));//const CGAffineTransform *m

        CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), pathRef,NULL );//CFDictionaryRef frameAttributes

        CGContextTranslateCTM(context, 0, -self.bounds.size.height);

        CGContextSetTextPosition(context, 0, 0);

        CTFrameDraw(frame, context);

        CGContextRestoreGState(context);

        CGPathRelease(pathRef);

        CFRelease(framesetter);

        UIGraphicsPushContext(context);

    }

}

 

- (void)dealloc

{

    [_titleActionView release]; _titleActionView = nil;

    [_textActionView release]; _textActionView = nil;

    if(_mutableLineActionView != nil){[_mutableLineActionView release]; _mutableLineActionView = nil;}

    [attributedString release];

    [super dealloc];

}

 

@end

 

 

测试用例:

- (void)viewDidLoad

{

    [super viewDidLoad];

    MutableLabel *label = [[MutableLabel alloc]initWithFrame:CGRectMake(0, 50, 300, 100)];

    [self.view addSubview:label];

    NSString *str = @"575757755575757575858575757556655656655656576556151445455411561";

    [label setTitle:@"阎晓薇" withFont:[UIFont systemFontOfSize:16] titleColor:[UIColor redColor] andText:str andTextFont:[UIFont systemFontOfSize:16] andTextColor:[UIColor blackColor]];

//    label.numberOfLines = 0;

    label.lineBreakMode = NSLineBreakByCharWrapping;

//    [label setText:str withFont:[UIFont systemFontOfSize:14] andColor:[UIColor blackColor]];

//    [label setTitle:@"阎晓薇" withFont:[UIFont systemFontOfSize:14] andColor:[UIColor redColor]];

    

    [label addTargetToTitle:self action:@selector(titleClicked)];

    [label addTargetToText:self action:@selector(textClicked)];

    [label release];

}

 

-(void)titleClicked

{

    NSLog(@"titleClicked");

}

 

-(void)textClicked

{

    NSLog(@"textClicked");

}

两种实现方式,代码有点累赘