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 = 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");

}

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

label显示不同的字体颜色,布布扣,bubuko.com

时间: 2024-12-04 17:12:47

label显示不同的字体颜色的相关文章

UILable显示不同的字体颜色、字体大小、行间距、首行缩进、下划线等属性(NSMutableAttributedString)

案例1:修改文本字体大小.颜色属性 比如文本展示为姓名和性别,但是我们不能排除姓名会很长,所以此刻的lable宽度我们就不能写死,换句话说lable的宽度根据文本的内容来定 我经常用两种方式解决: 1.前面文章已经涉及:lable自适应http://blog.csdn.net/tuwanli125/article/details/51003798 2.就是使用NSMutableAttributedString属性给infoL设置文本 NSString *infoStr = [NSStringst

Label显示不同颜色和字体

在一个UILabel 使用不同的颜色或不同的字体来体现字符串,在iOS 6 以后我们可以很轻松的实现这一点,官方的API 为我们提供了UILabel类的attributedText, 使用不同颜色和不同字体的字符串,我们可以使用NSAttributedText 和 NSMutableAttributedText 类来实现.如果想在iOS6.0以前版本实现这个效果,需要使用到一个第三方库TTTAttributedLabel,同时还有导入CoreText.frame框架. @interface Vi

label显示不同颜色的字体

NSString *contentSrt = [NSString stringWithFormat:@"%@ (%@)",categoryModel.categoryName, categoryModel.phoneCount]; NSRange rang = [contentSrt rangeOfString:categoryModel.categoryName]; NSMutableAttributedString *attStr = [[NSMutableAttributedSt

改变label中的某字体颜色

NSString *[email protected]"你家在哪里,需要我送你么"; NSString *[email protected]"在哪里"; UILabel *stringLabel=[[UILabel alloc]init]; stringLabel.frame=CGRectMake(0, 100, 300, 30); stringLabel.font=[UIFont systemFontOfSize:17]; stringLabel.backgrou

printf 字体颜色打印

为了给printf着色方便, 我们可以定义一些宏: view plain copy to clipboard print ? #define NONE          "/033[m" #define RED           "/033[0;32;31m" #define LIGHT_RED     "/033[1;31m" #define GREEN         "/033[0;32;32m" #define LI

应用键横竖屏切换;label中显示图片;不同类型设备适配的代码;UIWebView字体大小、字体颜色、背景色的设置;

最近总结的工作中遇到的小问题在这里共享 ,希望对大家能有帮助 1.横屏的一个应用在修改个人资料过程从相册取图片或者拍照的过程中,横纵屏切换引起再次进入程序时应用变纵屏的bug --------------主页面控制器中点击进入个人资料页面的地方:---------------------- - (void)changepersonIcon{ UIActionSheet*actionSheet = [[UIActionSheetalloc] initWithTitle:@"选择封面图片"

设置一个label显示多种颜色,多种字体大小

UILabel* label = [[UILabel alloc] init]; label.frame = CGRectMake(0, 100, 200, 100); label.textColor = [UIColor blackColor]; NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"1234567890"]; NSRange range = NSMak

raid及mdadm命令之一(含shell显示字体颜色等)

写一个脚本: 1)显示一个菜单给用户: d|D)    show disk usages. m|M)    show memory  usages. s|S)    show swap usages. quit|q)    quit. 2)当用户给定选项后显示相应的内容 当用户选择完成,显示相应信息后,不退出,而是让用户再一次选择,直到选择quit或q #!/bin/bash while  [ 1 -eq 1 ]  ; do echo " " read -p "d|D)  

tableview 点击cell改变cell中的label.text的字体颜色,cell复用出现问题的解决方案2

关于Cell的复用问题,上次已经说了一种,但似乎那种方法不是最好的,所以说,今天下午根据别人提示,想到了此方法.还是老样子,可能不是最好的,但是实现了功能,至少比上次的要好一些. 题目要求:定义固定数据源,然后让tableview的行上各自显示第几行,然后点击选中的时候,字体颜色会变为红色,取消选中的时候字体变为黑色.然后最后的时候要输出选中的结果 解题思路:首先实现tableView的几个协议,然后定义一个模型,在模型中定义一个标识,然后通过点中的时候标识,然后判断标识解决Cell的复用. M