Swift 修改字符串的范围颜色 NSAttributedString NSMutableAttributedString

Swift 修改字符串的范围颜色 NSAttributedString NSMutableAttributedString

需求:

获取 StoryBoard 中字义的 Label,根据需要设置 Label 内文字的一部分为一个颜色,另一部分为另一个颜色,如下图

在这里插入图片描述

实现所需知识

这里需要用到 NSAttributedStringNSMutableAttributedString,这两个都是 iOS 中最常用的文字表示形式,它包含文字的颜色,边框,大小,字体等等等等,所有 NSAttributedString.Key 里列举的属性都可以定义。

官方文档中的说明: https://developer.apple.com/documentation/foundation/nsattributedstring/key

先说说区别:

类名说明
NSAttributedString一次生成,不能修改属性,不能修改文字内容
NSMutableAttributedString可以修改内部的属性值,不能修改文字内容

NSAttributedString.Key 一些常用属性的说明

属性值说明
.foregroundColor文字颜色
.strokeColor描边颜色
.strokeWith描边大小
.font字体: 相关字体的属性去字体里面设置,大小,字体类型等等

实现

我是在一个 TableViewController 中修改 Cell 的某个 Label ,外面的代码不写了,只解释里面的关于修改字符的部分

// 1. 获取 StoryBoard 中 Label 的原有属性
let attributes = cell.labelTitle.attributedText!.attributes(at: 1, effectiveRange: NSRangePointer(bitPattern: 0))
    
// 2. 创建新的可编辑的字符对象
let mString = NSMutableAttributedString(string: String(sample.temperature),
                                        attributes: attributes)
    
// 3. 在生成的 NSMutableAttributedString 对象中修改前两位的颜色
mString.setAttributes(
    [NSAttributedString.Key.foregroundColor : UIColor.black],
    range: NSRange(location: 0, length: 2)
)
    
// 4. 修改后面剩余字符的颜色
mString.setAttributes(
    [NSAttributedString.Key.foregroundColor : Colors.magenta],
    range: NSRange(location: 3, length: mString.string.count - 3)
)

// 5. 把修改好的 NSMutableAttributedString 重新赋值给 Label
cell.labelTitle.attributedText = mString

结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十月ooOO

许个愿,我帮你实现

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值