iOS开发之NSAttributedString使用

2023-05-16

本文介绍了NSAttributedString和NSMutableAttributedString的简单用法.

一. NSAttributedString介绍

  • 摘自NSAttributedString.h文件
@interface NSAttributedString : NSObject <NSCopying, NSMutableCopying, NSSecureCoding>
  • 它由2部分组成
    1.文字内容 : NSString *
    2.文字属性: NSDictionary *
文字颜色 - NSForegroundColorAttributeName
字体大小 - NSFontAttributeName
下划线 - NSUnderlineStyleAttributeName
背景色 - NSBackgroundColorAttributeName

二.NSMutableAttributedString介绍

  • 摘自NSAttributedString.h文件
@interface NSMutableAttributedString : NSAttributedString
  • NSMutableAttributedString常用的有三种方法:
    1.设置range范围的属性, 重复设置同一个范围的属性, 后面一次设置会覆盖前面的设置.
  - (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs   range:(NSRange)range;

2.添加range范围的属性, 同一个范围, 可以不断添加属性.

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

3.一次性添加一个范围内的多个属性.

  - (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range;

三.需求

  • 给文本框设置占位文字的字体颜色、背景颜色以及下划线.
    通过xib或者storyboard创建的界面,在界面右侧是找不到对应的设置属性.

四.解决

  • 方法1.
    通过NSAttributedString实现,自定义一个继承至UITextField的类,在awakeFromNib方法中写以下代码.
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
attributes[NSForegroundColorAttributeName] = [UIColor yellowColor];
attributes[NSBackgroundColorAttributeName] = [UIColor redColor];
attributes[NSUnderlineStyleAttributeName] = @YES;
self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"o惜乐o" attributes:attributes];

效果图如下:

效果图

  • 注意 : 别忘记指定UITextField的Class
    如图:

关联UITextField的Class

  • 方法2:
    通过NSMutableAttributedString实现.代码如下:
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"o惜乐o"];
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
attributes[NSForegroundColorAttributeName] = [UIColor yellowColor];
attributes[NSBackgroundColorAttributeName] = [UIColor redColor];
attributes[NSUnderlineStyleAttributeName] = @YES;
[string setAttributes:attributes range:NSMakeRange(0, 4)];
self.attributedPlaceholder = string;
  • 方法3:
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"o惜乐o"];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(0, 4)];
[string addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 4)];
[string addAttribute:NSUnderlineStyleAttributeName value:@YES range:NSMakeRange(0, 4)];
self.attributedPlaceholder = string;
  • 方法4:
    重写drawPlaceholderInRect方法
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
attributes[NSForegroundColorAttributeName] = [UIColor whiteColor];
attributes[NSBackgroundColorAttributeName] = [UIColor redColor];
attributes[NSFontAttributeName] = self.font;
attributes[NSUnderlineStyleAttributeName] = @YES;
CGPoint placeholderPoint = CGPointMake(0, (rect.size.height - self.font.lineHeight) * 0.5);
[self.placeholder drawAtPoint:placeholderPoint withAttributes:attributes];
  • 方法5:
    通过视图分层可以看出,UITextField中包含UITextFieldLabel.

视图分层

  • 而占位视图是通过什么来显示呢?
    根据self.subviews.lastObject.class,可知占位图是通过UITextFieldLabel显示的,根据self.subviews.lastObject.superClass可知UITextFieldLabel的父类是UILabel,所以可以使用.textColor方法去显示文字颜色.但是,不能保证self.subviews.lastObject.class方法中取到的一定是UITextFieldLabel.所以运行时就上场了.
  • 因为UITextFieldLabel在UITextField.h头文件中找不到具体内容,只是简单的@class声明一下,所以需要利用运行时,查看UITextField的成员变量或属性,结果,你高兴的发现了这个家伙 – placeholderLabel,这时候可以理解为placeholderLabel属性指向UITextFieldLabel所对应的内容,所以占位视图也是placeholderLabel啦!!!那么,也可以通过.textColor设置颜色.
unsigned int count;
Ivar *ivarList = class_copyIvarList([UITextField class], &count);
for (int i = 0; i < count; i++)
{
    Ivar ivar = ivarList[i];
    NSString *str = [NSString stringWithUTF8String:ivar_getName(ivar)];
    NSLog(@"%@", str);
    }
free(ivarList);
  • 用KVC最终得出:
static NSString * const kPlaceholderColorKey = @"placeholderLabel.textColor";
static NSString * const kPlaceholderBGColorKey = @"placeholderLabel.backgroundColor";
[self setValue:[UIColor yellowColor] forKeyPath:kPlaceholderColorKey];
[self setValue:[UIColor redColor] forKeyPath:kPlaceholderBGColorKey];

设置下划线无法用KCV实现,如果非要用,还是会绕回第一种写法

NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
attributes[NSUnderlineStyleAttributeName] = @YES;
NSAttributedString *attributeText = [[NSAttributedString alloc] initWithString:@"o惜乐o" attributes:attributes];
[self setValue:attributeText forKeyPath:kPlaceholderUnderLineKey];
  • 说明:
    UITextFieldLabel的父类为UILabel.UILabel中有TextColor属性,而UILabel继承自UIView,UIView中有backgroundColor属性.所以UITextFieldLabel就可以设置文字颜色和背景颜色.而placeholderLabel是程序内部私有的属性,指向UITextFieldLabel的内容,所以也能设置文字颜色和背景颜色.

简书

iOS开发之NSAttributedString使用

个人博客

iOS开发之NSAttributedString使用

GitHub

NSAttributedStringDemo

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

iOS开发之NSAttributedString使用 的相关文章

  • WIN10 anaconda 安装 tensorflow-gpu不出错的最佳解决办法(不在系统安装CUDA)

    来源 xff1a https www pugetsystems com labs hpc The Best Way to Install TensorFlow with GPU Support on Windows 10 Without I
  • PostgreSQL教程

    一 PostgreSQL介绍 PostgreSQL是一个功能强大的 开源 的关系型数据库 底层基于C实现 PostgreSQL的开源协议和Linux内核版本的开源协议是一样的 BDS协议 xff0c 这个协议基本和MIT开源协议一样 xff
  • you-get的安装与使用

    youget简介 you get是github上python的一个开源库 https github com soimort you get xff0c 使用you get你只需要取得视频所在网页链接地址就可以很轻松的下载下来 xff0c 目
  • VS Code搭建PYQT5环境并创建Helloworld实例

    使用Python pip安装PyQt5和PyQt5 tool pip install PyQt5 pip install PyQt5 tools 在VS code中安装插件PYQT Integration 配置PYQT Integratio
  • ubuntu Xrdp远程连接Authentication is required to create a color managed device

    问题 Gnome Bug xff1a 无法点击 永不消逝的授权对话框 解决 xff1a https blog csdn net wu weijie article details 108481456
  • Linux运维入门~21.系统磁盘管理,解决u盘连接电脑无反应,解决卸载u盘正忙问题

    本节我们来了解一下linux系统的磁盘管理 识别设备常用命令有 xff1a fdisk l 查看真实存在的设备 cat proc partition 系统识别的设备 blkid 系统可使用的设备 df 系统正在挂载的设备 du 查看磁盘容量
  • 快速幂取模:求 a^b % N(C++)

    在某些情况下 xff0c 我们需要求模 N 情况下某个数的多次幂 xff0c 例如 xff1a 求多次幂结果的最后几位数 RSA算法的加解密 如果底数或者指数很大 xff0c 直接求幂再取模很容易会出现数据溢出的情况 xff0c 产生错误的
  • 新手教程:手把手教你使用Powershell批量修改文件名

    适合完全没用过 xff0c 没了解过powershell的人 1 打开Windows Powershell ISE 在任务栏搜索框中输入ISE xff0c 然后打开 xff08 我的任务栏放在右边了 xff0c 所以是这个样子 xff09
  • Mac OS 开机密码重置

    通过 Mac OS 恢复功能启动 Apple 芯片 xff1a 将 Mac 开机并继续按住电源按钮 xff0c 直至看到启动选项窗口 选择标有 选项 字样的齿轮图标 xff0c 然后点按 继续 Intel 处理器 xff1a 将 Mac 开
  • 表达式求值:从“加减”到“带括号的加减乘除”的实践过程

    本文乃Siliphen原创 xff0c 转载请注明出处 xff1a http blog csdn net stevenkylelee 为什么想做一个表达式求值的程序 最近有一个需求 xff0c 策划想设置游戏关卡的某些数值 xff0c 这个
  • Linux中source命令,在Android build 中的应用

    source命令 xff1a source命令也称为 点命令 xff0c 也就是一个点符号 xff08 xff09 source命令通常用于重新执行刚修改的初始化文件 xff0c 使之立即生效 xff0c 而不必注销并重新登录 用法 xff
  • Edge 错误代码: STATUS_ACCESS_DENIED 解决方案

    1 到C盘Edge的文件全部删掉 2 到电脑管家的软件管理重新下载Edge 或者 去官网下载 3 再次打开Edge xff0c 功能都回来了 注 xff1a 该解决方案源自于edge吧的四川男篮大佬
  • centos7.9离线安装mysql5.7

    前言 windows server2003服务器 xff0c 安装mysql提示需要net framework xff0c 费了半天劲装好了 xff0c 发现解压版redis无法启动 xff0c 换了个低版本也是无法安装 xff0c 服务器
  • vs2019-slicer编译问题记录

    3D Slicer编译过程问题记录 官网教程 xff1a https slicer readthedocs io en latest developer guide build instructions windows html 环境 CM
  • sudo npm command not found 问题解决

    这种情况通常是使用 npm 命令可以正常使用 xff0c 但使用sudo npm 命令便会报 command not found 这是什么原因呢 xff1f 输入which npm可以得到 usr local bin npm xff0c 这
  • (POJ1201)Intervals <差分约束系统-区间约束>

    Intervals Description You are given n closed integer intervals ai bi and n integers c1 cn Write a program that reads the
  • 【sv与c】sv与c交互

    网上此类文章很多 xff0c 这里暂时不放具体实现和测试结果 xff0c 后续持续更新 下面引用一些帖子 xff0c 帖子中涉及到具体做法 vcs联合编译v sv c 43 43 代码 sxlwzl的专栏 CSDN博客 1 xff0c 假设
  • stm32f103c8t6最小系统

    提示 xff1a 文章写完后 xff0c 目录可以自动生成 xff0c 如何生成可参考右边的帮助文档 文章目录 前言stm32f103c8t6构成二 xff1a 电源电路稳压模块注意 复位电路NRST 时钟电路程序下载电路JTAGSWD 启
  • udp中的connect()&bind()

    connect amp bind 的作用 udp udp connect span class hljs preprocessor include lt sys types h gt span span class hljs preproc
  • Linux Hook技术实践

    LInux Hook技术实践 什么是hook 简单的说就是别人本来是执行libA so里面的函数的 xff0c 结果现在被偷偷换成了执行你的libB so里面的代码 xff0c 是一种替换 为什么hook 恶意代码注入调用常用库函数时打lo

随机推荐

  • Tensorflow Cnn mnist 的一些细节

    Tensorflow cnn MNIST 笔记 写这个完全是记录看官网example时不懂 xff0c 但后来弄懂的一些细节 当然这个可以算是对官方文档的补充 xff0c 也许每个人遇到的不懂都不一样 xff0c 但希望对大家有帮助 先上代
  • effective cpp 读书笔记2

    当你用到多态时 xff0c 务必把析构函数做成虚函数 以前知道子类的析构函数会自动调用父类的析构函数 xff0c 然而今天却发现不总是这样 当你用基类的指针指向派生类时 xff0c 然后delete这个指针时 xff0c 有可能就不会调用派
  • malloc与缺页的一些的时间测量

    malloc与缺页的一些的时间测量 时间函数 span class hljs keyword struct span timespec time t tv sec span class hljs keyword long span span
  • N皇后问题的并行解法

    N皇后问题的并行解法 N皇后问题 其实就是一个n n的棋盘上摆n个皇后 xff0c 任意两个皇后不能同行 xff0c 同列 xff0c 同对角线 xff0c 求出所有的摆法 这个问题可以看做是求n的组合数 比如第一列上的皇后在第x1行 xf
  • apache服务器使用时网页乱码问题

    查看原文 xff1a http www hellonet8 com 440 html 在apache的配置文件httpd conf中 xff0c 或许我们会用到 AddDefaultCharset UTF 8 来设置所有主机或者某虚拟主机的
  • 将群晖NAS变为本地盘

    本文介绍一个工具 xff0c 可以在 Windows 系统下将群晖NAS的目录变为本地盘 xff0c 好处是在外部访问的时候 xff0c 能够大大改善体验 可以用本地的应用程序直接打开 xff0c 速度依赖网络带宽 xff0c 正常情况下
  • Deepin | 修改网卡名 | 配置IP地址 | DHCP

    文章目录 修改网卡名解决方案 xff1a 配置IP地址解决方案 xff1a DHCP自动获取 修改网卡名 解决方案 xff1a 禁用该可预测命名规则 span class token function sudo span vim etc d
  • windows商店直接安装ubuntu子系统

    文章目录 安装报错WslRegisterDistribution failed with error 0x8007019eWSL安装Linux报错WslRegisterDistribution failed with error 0x803
  • 基于VTK的任意平面切割

    这位 小兵 太传奇了 xff0c 先收藏 xff0c 再学习 xff0c http www cnblogs com dawnWind archive 2013 02 17 3D 06 html 先贴码 以后再 切割介绍 对于一个模型的切割需
  • 百度OCR接口使用

    最近在研究ocr识别 也对比了一些的方法 现在来介绍一下 调用百度提供的ocr接口 小量调用的话 是不收费的 1 首先 你要有一个百度账号 如果已经有的话 登录进去会进入到这样一个界面 点击 34 创建应用 34 创建成功后 返回应用列表
  • Python 元组(tuple)剖析详解

    目录 概念元组的常见操作 概念 元组 span class token punctuation span 是一个有序 span class token punctuation span 可重复的集合 特点 span class token
  • Dom型XSS跨站脚本攻击和防御

    在前面的文章中 xff0c 我们讲了持久型XSS和反射型XSS 我个人觉得这些命名真的很贴切 xff0c 反应了概念的本质 无论是持久型XSS还是反射型XSS 恶意的js脚本内容都需要由服务端返回给用户 xff0c 今天我们要说的Dom型X
  • 编译错误导致浪费10多分钟, 编译错误的提示:xxx does not name a type xxx

    最近 xff0c 我在google protobuf 协议文件xxx pb增加了结构体 类 请求字段 xff0c 生成xxx h和xxx cpp文件 xff0c 然后放到对应目录进行编译 xff0c 奇葩的是 xff0c 编译出错 xff0
  • 树莓派上安装php

    简单东西 xff1a sudo apt get install php 然后 xff1a pi 64 raspberrypi taoge cat test php lt php aa 61 60 echo 39 hello 39 39 xx
  • 结构体和数组

    结构体中可以有数组类型的成员 xff0c 数组的元素也可以是结构体 数组和结构体的初始化是一样的 xff0c 都是把各个元素放在一个大括号里 xff0c 各个成员用逗号分隔 结构体数组使用示例 include lt stdio h gt i
  • iOS聊天室 简单的对话聊天界面(cell自适应高度)

    文章目录 难点思路需要用到的方法的大致解析 xff08 只是简单的介绍 xff0c 如果想要仔细理解推荐再去看看别的博客 xff09 GitHub地址代码效果图 难点 因为聊天长度不一样 xff0c 需要设置自适应高度发送信息后 xff0c
  • navicat链接centos7数据库失败Authentication plugin ‘caching_sha2_password‘ cannot be loaded: dlopen(../Frame

    重新配置云上数据库 mysql u root p use mysql select user host plugin authentication string from user G ALTER USER root 64 IDENTIFI
  • C语言中以字符串形式输出枚举变量

    1 枚举应用说明 每个枚举常量对应一个整形数字 xff0c 很多时候可以像整形一样使用 xff1b 但是如果要求打印枚举变量名的字符串 xff0c 办法也有很多 xff0c 查看网上方法几乎都需要转换 xff0c 要么用数组 xff0c 下
  • 定时器初值的计算方法

    定时器初值的计算方法 1 xff1a 定义 用户时间 xff1a Tuser 寄存器位数 xff1a Rn xff08 n 为 8 16 32分别代表 0xFF 0xFFFF 0xFFFFFFFF xff09 初始值 xff1a TCONH
  • iOS开发之NSAttributedString使用

    本文介绍了NSAttributedString和NSMutableAttributedString的简单用法 一 NSAttributedString介绍 摘自NSAttributedString h文件 span class hljs c