iOS 文字样式处理总结(字体、前背景色、斜体、加粗、对齐、行间距、段间距、动态获取字符串label宽高等)...

2023-05-16

在iOS开发中,常常会有一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求。NSMuttableAttstring(带属性的字符串),可以灵活实现以上功能。 NSMutableParagraphStyle段落风格,设置行间距、段间距、缩进、对齐方式等。

  1. 实例化方法和使用方法 实例化方法: 使用字符串初始化
  • (id)initWithString:(NSString *)str;//例:NSMutableAttributedString *AttributedStr = [[NSMutableAttributedStringalloc]initWithString:@"文字样式处理"];

字典中存放一些属性名和属性值:

  • (id)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;//如:NSDictionary *attributeDict = [NSDictionarydictionaryWithObjectsAndKeys: [UIFontsystemFontOfSize:15.0],NSFontAttributeName, [UIColorredColor],NSForegroundColorAttributeName, NSUnderlineStyleAttributeName,NSUnderlineStyleSingle,nil];NSMutableAttributedString *AttributedStr = [[NSMutableAttributedStringalloc]initWithString:@"文字样式处理" attributes:attributeDict];

使用NSAttributedString初始化,跟NSMutableString,NSString类似:

  • (id)initWithAttributedString:(NSAttributedString *)attester;

使用方法: 为某一范围内文字设置多个属性

  • (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;

为某一范围内文字添加某个属性

  • (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

为某一范围内文字添加多个属性

  • (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;

移除某范围内的某个属性

  • (void)removeAttribute:(NSString *)name range:(NSRange)range;
  1. 常见的属性及说明

NSFontAttributeName //字体  NSParagraphStyleAttributeName //段落格式 NSForegroundColorAttributeName //字体颜色 NSBackgroundColorAttributeName //背景颜色  NSStrikethroughStyleAttributeName //删除线格式  NSUnderlineStyleAttributeName //下划线格式  NSStrokeColorAttributeName //删除线颜色  NSStrokeWidthAttributeName//删除线宽度 NSShadowAttributeName //阴影 NSParagraphStyleAttributeName//段落的风格(设置首行,行间距,对齐方式什么的)

NSMutableParagraphStyle paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineSpacing = 10;// 字体的行间距 paragraphStyle.firstLineHeadIndent = 20.0f;//首行缩进 paragraphStyle.alignment = NSTextAlignmentJustified;//(两端对齐的)文本对齐方式:(左,中,右,两端对齐,自然) paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;//结尾部分的内容以……方式省略 ( "...wxyz" ,"abcd..." ,"ab...yz") paragraphStyle.headIndent = 20;//整体缩进(首行除外) paragraphStyle.tailIndent = 20;// paragraphStyle.minimumLineHeight = 10;//最低行高 paragraphStyle.maximumLineHeight = 20;//最大行高 paragraphStyle.paragraphSpacing = 15;//段与段之间的间距 paragraphStyle.paragraphSpacingBefore = 22.0f;//段首行空白空间/ Distance between the bottom of the previous paragraph (or the end of its paragraphSpacing, if any) and the top of this paragraph. / paragraphStyle.baseWritingDirection = NSWritingDirectionLeftToRight;//从左到右的书写方向(一共三种) paragraphStyle.lineHeightMultiple = 15;// Natural line height is multiplied by this factor (if positive) before being constrained by minimum and maximum line height. *// paragraphStyle.hyphenationFactor = 1;//连字属性 在iOS,唯一支持的值分别为0和1

两个样式枚举
typedef NS_ENUM(NSInteger, NSLineBreakMode) {/* What to do with long lines */ 
NSLineBreakByWordWrapping = 0, /* Wrap at word boundaries, default */
 NSLineBreakByCharWrapping,/* Wrap at character boundaries */ 
NSLineBreakByClipping,/* Simply clip */剪掉后面显示不了的部分 
NSLineBreakByTruncatingHead,/* Truncate at head of line: "...wxyz" */头部分的内容以……方式省略 
NSLineBreakByTruncatingTail,/* Truncate at tail of line: "abcd..." */结尾部分的内容以……方式省略 
NSLineBreakByTruncatingMiddle/* Truncate middle of line: "ab...yz" */中间部分的内容以……方式省略 
} NS_ENUM_AVAILABLE_IOS(6_0); 
typedef NS_ENUM(NSInteger, NSWritingDirection) { 
NSWritingDirectionNatural = -1, // Determines direction using the Unicode Bidi Algorithm rules P2 and P3  
NSWritingDirectionLeftToRight = 0, // Left to right writing direction 左到右的书写方向  
NSWritingDirectionRightToLeft = 1 // Right to left writing direction 右到左的书写方向 
} NS_ENUM_AVAILABLE_IOS(6_0);
复制代码
/* NSFontAttributeName 字体大小 
NSParagraphStyleAttributeName 段落的风格(设置首行,行间距,对齐方式什么的) 
NSKernAttributeName 字间距 */
 NSDictionary *attributes = @{ 
NSFontAttributeName:[UIFont systemFontOfSize:15], 
NSParagraphStyleAttributeName:paragraphStyle, 
NSKernAttributeName:@(10), 
}; 
textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];
复制代码

再来个实例

//随便定义一个字符串,做测试使用 
NSString *massageStr = @"\t北京乌托邦有限公司(以下简称“乌托邦”)在此特别提醒您(用户)在注册成为用户之前,请认真阅读本《用户协议》(以下简称“协议”),确保您充分理解本协议中各条款。请您审慎阅读并选择接受或不接受本协议。除非您接受本协议所有条款,否则您无权注册、登录或使用本协议所涉服务。您的注册、登录、使用等行为将视为对本协议的接受,并同意接受本协议各项条款的约束。\r\n \t本协议约定乌托邦与用户之间关于“乌托邦”软件服务(以下简称“服务”)的权利义务。“用户”是指注册、登录、使用本服务的个人。本协议可由乌托邦随时更新,更新后的协议条款一旦公布即代替原来的协议条款,恕不再另行通知,用户可在本网站查阅最新版协议条款。在乌托邦修改协议条款后,如果用户不接受修改后的条款,请立即停止使用乌托邦提供的服务,用户继续使用乌托邦提供的服务将被视为接受修改后的协议。"; 
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:massageStr]; 
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:20];
//调整行间距
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.agreementText length])];
[attributedString addAttribute:NSForegroundColorAttributeName value:
[UIColor redColor] range:NSMakeRange(0, 12)]; // 0为起始位置 length是从起始位置开始 设置指定颜色的长度 
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(18, 3)]; //设置尺寸 
[attributedString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(18, 3)]; // 0为起始位置 length是从起始位置开始 设置指定字体尺寸的长度
复制代码

根据字符串获取宽高 根据宽度求高度 content 计算的内容 width 计算的宽度 font字体大小

+ (CGFloat)getHeightWithContent:(NSString *)content width:(CGFloat)width font:(CGFloat)font{ 
CGRect rect = [content boundingRectWithSize:CGSizeMake(width, 999) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{
NSFontAttributeName:[UIFont systemFontOfSize:font]}  context:nil]; 
return rect.size.height;
}
复制代码

根据高度度求宽度 content 计算的内容 Height 计算的高度 font字体大小

+ (CGFloat)getWidthWithContent:(NSString *)content height:(CGFloat)height font:(CGFloat)font{ 
CGRect rect = [content boundingRectWithSize:CGSizeMake(999, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{
NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil]; 
return rect.size.width;
}
复制代码

实际上,设置删除线

NSStrikethroughColorAttributeName 的时候,值也是这个枚举。

// NSUnderlineStyleNone 不设置下划线/删除线

// NSUnderlineStyleSingle 设置下划线/删除线为细的单线

// NSUnderlineStyleThick 设置下划线/删除线为粗的单线

// NSUnderlineStyleDouble 设置下划线/删除线为细的双线

// NSUnderlinePatternSolid 设置下划线/删除线样式为连续的实线

// NSUnderlinePatternDot 设置下划线/删除线样式为点,也就是虚线,比如这样:------

// NSUnderlinePatterDash 设置下划线/删除线样式为破折号,比如这样:—— —— ——

// NSUnderlinePatternDashDot 设置下划线/删除线样式为连续的破折号和点,比如这样:——-——-——-

// NSUnderlinePatternDashDotDot 设置下划线/删除线样式为连续的破折号、点、点,比如:——--——--——--

// NSUnderlineByWord 在有空格的地方不设置下划线/删除线
在设置以上属性时,可以以|分隔,同时设置多个属性
复制代码
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS 文字样式处理总结(字体、前背景色、斜体、加粗、对齐、行间距、段间距、动态获取字符串label宽高等)... 的相关文章

  • PHP+AJAX实现账号注册和登陆,附可用demo

    前言 登陆和注册已经是网站的标配了 xff0c 所以这是我们web开发学习过程中必学的了 其实很容易实现 xff0c 只需要懂数据库的增删改查 xff0c 还有if else的条件语句即可做出来 目录 css Login Reg css s
  • ftp服务器无法使用浏览器访问解决方法

    浏览器默认工作在被动模式 可能你的环境无法让ftp服务器工作在主动模式 这个很容易测试 你在IE浏览器的工具 internet选项 高级中取消使用被动ftp的设置 xff0c 看看浏览器是否还可以访问ftp服务器 xff0c 如果访问不了
  • Python抓取糗事百科成人版图片

    最近开始学习爬虫 xff0c 一开始看的是静觅 的爬虫系列文章 xff0c 今天看到糗事百科成人版 xff0c 心里就邪恶了一下 xff0c 把图片都爬下来吧 xff0c 哈哈 虽然后来实现了 xff0c 但还是存在一些问题 xff0c 暂
  • vc中调用Com组件的方法详解

    Requirement 1 创建myCom dll 该COM只有一个组件 两个接口IGetRes 方法Hello IGetResEx 方法HelloEx xff1b 2 在工程中导入组件或类型库 import 34 组件所在目录myCom
  • matlab练习程序(二值图像内外边界跟踪)

    目标内边界的像素全都在目标里面 xff0c 目标外边界的像素全都不在目标上 xff0c 是包围着目标的 二值图像内外边界的计算都是有两种方法的 xff0c 所以一共是4种算法 xff0c 不过实际用到跟踪的只有一个而已 首先是内边界跟踪 x
  • 如何使用.NET开发全版本支持的Outlook插件产品(三)——全面控制

    插件项目所有代码都已经上传至 https github com VanPan TestOutlookAdding 进阶基础 COM查看 首先 xff0c 对于Outlook对象模型 xff0c MSDN早就有非常详细的介绍 xff0c 请直
  • Android中应用程序如何获得系统签名权限

    最近在做一个控制电视界面的应用 xff0c 模拟电视遥控器操作 xff0c 代码如下 public static void simulateKeystroke final int KeyCode new Thread new Runnabl
  • 使用PostSharp在.NET平台上实现AOP

    摘要 本文首先介绍AOP xff08 面向方面编程 xff09 的相关概念及理论 xff0c 然后介绍如何使用PostSharp框架在 NET平台上实现AOP xff0c 最后对PostSharp的机制及AOP的优劣进行一个简单的分析 AO
  • python 带头节点的单链表相关函数

    链表用头结点还是头指针让我混乱 在写append函数时 xff0c 发现网上的写法各有不同 xff0c 而带头结点的会更好理解 xff0c 也更简洁 以下是带头结点的单链表一些简单的相关函数 span class token keyword
  • 使用 Beautiful Soup 解析网页内容

    安装Beautiful Soup Beautiful Soup是一个Python的HTML解析框架 xff0c 我们可以利用它方便的处理HTML和XML文档 Beautiful Soup有3和4两个版本 xff0c 目前3已经停止开发 所以
  • ibm服务器报警指示灯含意

    EVENT LOG指示灯报警 有台IBM服务器前面的光通路面板开始亮起了小黄灯 xff0c 推出这个小盒子一看 xff0c 是EVENT LOG指示灯报警 一时不知道是什么原因 xff0c 可能是日志错误 xff0c 要进Configura
  • [概念学习] Virtualization的几个概念

    1 Vitualization xff1a 某种东西的虚拟版本 xff0c 比如硬件平台 操作系统 存储设备 网络资源等 the creation of a virtual version of something such as a ha
  • Windows2012、windows2016配置多用户登录

    windows系统多用户登录配置方法如下 xff0c 但是120天后还是会提示缺少远程桌面授权服务器 xff0c 根本解决办法 xff0c 请参考 xff1a https blog 51cto com 13777088 2299170 服务
  • 全自动迁移数据库的实现 (Fluent NHibernate, Entity Framework Core)

    在开发涉及到数据库的程序时 xff0c 常会遇到一开始设计的结构不能满足需求需要再添加新字段或新表的情况 xff0c 这时就需要进行数据库迁移 实现数据库迁移有很多种办法 xff0c 从手动管理各个版本的ddl脚本 xff0c 到实现自己的
  • VM virtuaBox异常关机启动不了的解决方案

    事件回放 我的物理机是win7 xff0c 上面装了一个 VM virtualBox 用来装 Centos xff0c 有天物理机非正常关闭 xff0c 导致 VM virtuaBox异常关机启动不 了 xff0c 如下 确实找不到这个vm
  • SpringMVC系列(十一)把后台返回的数据转换成json、文件下载、文件上传

    一 后台返回的数据转换成json 1 引入转换json需要的3个依赖 1 lt json转换需要的依赖 begin gt 2 lt dependency gt 3 lt groupId gt com fasterxml jackson co
  • html 复选框checkbox

    阅读目录 统计选中复选框的个数点击复选框 xff0c 执行相应的函数复选框的状态层次关系 xff0c 选中父节点 xff0c 子节点全部选中 回到顶部 统计选中复选框的个数 lt html gt lt head gt lt title gt
  • android kk界面旋转流程_Android屏幕旋转前180度旋转以正确定向

    由于硬件问题 xff0c 我们必须将我们开发的Android平板电脑上下180度安装 我们设法翻转屏幕回来做以下修改 xff0c 以正确的方向 xff1a Android屏幕旋转前180度旋转以正确定向 框架 基 服务 SurfaceFli
  • 理解 简单的递归实现阶乘过程中的参数传递

    span class token keyword def span span class token function factorial span span class token punctuation span n span clas
  • 程序员工作中的一些建议

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 一 尽早地添加日志记录和错误处理 在开发新系统时 xff0c 我做的第一件事就是添加日志和错误处理 xff0c 因为这两者从一开始就非常有用 如果系统不能照常工作 xff0

随机推荐