UILabel上展示不同颜色的文字(NSAttributedString)

2024-06-08 10:32

本文主要是介绍UILabel上展示不同颜色的文字(NSAttributedString),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

【提示:最好的方法在最后哦!O(∩_∩)O~】

首先导入CoreText.framework,并在需要使用的文件中导入:

#import<CoreText/CoreText.h>

新建一个类,继承UILabel,以下为文件内容:

MyLabel.h

//MyLabel.h
#import <Foundation/Foundation.h>
#import <CoreText/CoreText.h>@interface MyLabel : UILabel@end

MyLabel.m

//MyLabel.m
#import "MyLabel.h"@implementation MyLabel//NSAttributedString继承于NSObject,并且不支持任何draw的方法,那我们就只能自己draw了。
-(void)drawRect:(CGRect)rect{[super drawRect:rect];NSAttributedString *attriString = [self getAttributedString];//在代码中我们调整了CTM(current transformation matrix),这是因为Quartz 2D的坐标系统不同CGContextRef ctx = UIGraphicsGetCurrentContext();CGContextConcatCTM(ctx, CGAffineTransformScale(CGAffineTransformMakeTranslation(0, rect.size.height), 1.f, -1.f));//CTFramesetter是CTFrame的创建工厂,NSAttributedString需要通过CTFrame绘制到界面上,得到CTFramesetter后,创建path(绘制路径),然后得到CTFrame,最后通过CTFrameDraw方法绘制到界面上。CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attriString);CGMutablePathRef path = CGPathCreateMutable();CGPathAddRect(path, NULL, rect);CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), path, NULL);CFRelease(path);CFRelease(framesetter);CTFrameDraw(frame, ctx);CFRelease(frame);/*//------------------------------------------------------------------------//----------------取消注释,同样可以实现UILabel上展示不同样式的文字--------------//------------------------------------------------------------------------CATextLayer *textLayer = [CATextLayer layer];textLayer.string = [self getAttributedString];textLayer.frame = CGRectMake(0, 50, 200, 200);//可调整位置textLayer.backgroundColor = [UIColor purpleColor].CGColor;[self.layer addSublayer:textLayer];*/
}-(NSMutableAttributedString *)getAttributedString{//创建一个NSMutableAttributedStringNSMutableAttributedString *attriString = [[[NSMutableAttributedString alloc] initWithString:@"Come on,baby!Come on,baby!Come on,baby!"]autorelease];//把this的字体颜色变为红色[attriString addAttribute:(NSString *)kCTForegroundColorAttributeNamevalue:(id)[UIColor redColor].CGColorrange:NSMakeRange(0, 4)];//把is变为黄色[attriString addAttribute:(NSString *)kCTForegroundColorAttributeNamevalue:(id)[UIColor yellowColor].CGColorrange:NSMakeRange(5, 16)];//改变this的字体,value必须是一个CTFontRef[attriString addAttribute:(NSString *)kCTFontAttributeNamevalue:(id)CTFontCreateWithName((CFStringRef)[UIFont boldSystemFontOfSize:14].fontName,14,NULL)range:NSMakeRange(0, 4)];//给this加上下划线,value可以在指定的枚举中选择[attriString addAttribute:(NSString *)kCTUnderlineStyleAttributeNamevalue:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble]range:NSMakeRange(0, 4)];/*换行的实现如果想要计算NSAttributedString所要的size,就需要用到这个API:CTFramesetterSuggestFrameSizeWithConstraints,用NSString的sizeWithFont算多行时会算不准的,因为在CoreText里,行间距也是你来控制的。设置行间距和换行模式都是设置一个属性:kCTParagraphStyleAttributeName,这个属性里面又分为很多子属性,其中就包括kCTLineBreakByCharWrappingkCTParagraphStyleSpecifierLineSpacingAdjustment设置如下:*//*//-------------取消注释,实现换行-------------CTParagraphStyleSetting lineBreakMode;CTLineBreakMode lineBreak = kCTLineBreakByCharWrapping; //换行模式lineBreakMode.spec = kCTParagraphStyleSpecifierLineBreakMode;lineBreakMode.value = &lineBreak;lineBreakMode.valueSize = sizeof(CTLineBreakMode);//行间距CTParagraphStyleSetting LineSpacing;CGFloat spacing = 4.0;  //指定间距LineSpacing.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment;LineSpacing.value = &spacing;LineSpacing.valueSize = sizeof(CGFloat);CTParagraphStyleSetting settings[] = {lineBreakMode,LineSpacing};CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, 2);   //第二个参数为settings的长度[attriString addAttribute:(NSString *)kCTParagraphStyleAttributeNamevalue:(id)paragraphStylerange:NSMakeRange(0, attriString.length)];*/return attriString;
}@end

测试代码

先要 #import "MyView.h",在适当位置创建MyLabel的对象,并添加到View中

MyLabel *myLabel = [[MyLabel alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[self.view addSubview:myLabel];
[myLabel release];

效果图如下:




补充:另一种方式,利用NSMutableAttributedString,很简便

//iOS6以后 在UILabel显示不同的字体和颜色
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"Using NSAttributed String"];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0,5)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(6,12)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(19,6)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30.0] range:NSMakeRange(0, 5)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:10.0] range:NSMakeRange(6, 12)];
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Courier-BoldOblique" size:30.0] range:NSMakeRange(19, 6)];
self.attrLabel.attributedText = str;



这篇关于UILabel上展示不同颜色的文字(NSAttributedString)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1041926

相关文章

python+opencv处理颜色之将目标颜色转换实例代码

《python+opencv处理颜色之将目标颜色转换实例代码》OpenCV是一个的跨平台计算机视觉库,可以运行在Linux、Windows和MacOS操作系统上,:本文主要介绍python+ope... 目录下面是代码+ 效果 + 解释转HSV: 关于颜色总是要转HSV的掩膜再标注总结 目标:将红色的部分滤

MySQL中慢SQL优化的不同方式介绍

《MySQL中慢SQL优化的不同方式介绍》慢SQL的优化,主要从两个方面考虑,SQL语句本身的优化,以及数据库设计的优化,下面小编就来给大家介绍一下有哪些方式可以优化慢SQL吧... 目录避免不必要的列分页优化索引优化JOIN 的优化排序优化UNION 优化慢 SQL 的优化,主要从两个方面考虑,SQL 语

Vue项目的甘特图组件之dhtmlx-gantt使用教程和实现效果展示(推荐)

《Vue项目的甘特图组件之dhtmlx-gantt使用教程和实现效果展示(推荐)》文章介绍了如何使用dhtmlx-gantt组件来实现公司的甘特图需求,并提供了一个简单的Vue组件示例,文章还分享了一... 目录一、首先 npm 安装插件二、创建一个vue组件三、业务页面内 引用自定义组件:四、dhtmlx

Python如何计算两个不同类型列表的相似度

《Python如何计算两个不同类型列表的相似度》在编程中,经常需要比较两个列表的相似度,尤其是当这两个列表包含不同类型的元素时,下面小编就来讲讲如何使用Python计算两个不同类型列表的相似度吧... 目录摘要引言数字类型相似度欧几里得距离曼哈顿距离字符串类型相似度Levenshtein距离Jaccard相

在不同系统间迁移Python程序的方法与教程

《在不同系统间迁移Python程序的方法与教程》本文介绍了几种将Windows上编写的Python程序迁移到Linux服务器上的方法,包括使用虚拟环境和依赖冻结、容器化技术(如Docker)、使用An... 目录使用虚拟环境和依赖冻结1. 创建虚拟环境2. 冻结依赖使用容器化技术(如 docker)1. 创

关于Spring @Bean 相同加载顺序不同结果不同的问题记录

《关于Spring@Bean相同加载顺序不同结果不同的问题记录》本文主要探讨了在Spring5.1.3.RELEASE版本下,当有两个全注解类定义相同类型的Bean时,由于加载顺序不同,最终生成的... 目录问题说明测试输出1测试输出2@Bean注解的BeanDefiChina编程nition加入时机总结问题说明

java中不同版本JSONObject区别小结

《java中不同版本JSONObject区别小结》本文主要介绍了java中不同版本JSONObject区别小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们... 目录1. FastjsON2. Jackson3. Gson4. org.json6. 总结在Jav

Python中连接不同数据库的方法总结

《Python中连接不同数据库的方法总结》在数据驱动的现代应用开发中,Python凭借其丰富的库和强大的生态系统,成为连接各种数据库的理想编程语言,下面我们就来看看如何使用Python实现连接常用的几... 目录一、连接mysql数据库二、连接PostgreSQL数据库三、连接SQLite数据库四、连接Mo

java脚本使用不同版本jdk的说明介绍

《java脚本使用不同版本jdk的说明介绍》本文介绍了在Java中执行JavaScript脚本的几种方式,包括使用ScriptEngine、Nashorn和GraalVM,ScriptEngine适用... 目录Java脚本使用不同版本jdk的说明1.使用ScriptEngine执行javascript2.

2. c#从不同cs的文件调用函数

1.文件目录如下: 2. Program.cs文件的主函数如下 using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms;namespace datasAnalysis{internal static