获取 StoryBoard
中字义的 Label
,根据须要设置 Label 内文字的一部分为一个颜色,另外一部分为另外一个颜色,以下图swift
这里须要用到 NSAttributedString
和 NSMutableAttributedString
,这两个都是 iOS 中最经常使用的文字表示形式,它包含文字的颜色,边框,大小,字体等等等等,全部 NSAttributedString.Key
里列举的属性均可以定义。app
官方文档中的说明: https://developer.apple.com/documentation/foundation/nsattributedstring/key
先说说区别:字体
类名 | 说明 |
---|---|
NSAttributedString | 一次生成,不能修改属性,不能修改文字内容 |
NSMutableAttributedString | 能够修改内部的属性值,不能修改文字内容 |
NSAttributedString.Key
一些经常使用属性的说明属性值 | 说明 |
---|---|
.foregroundColor |
文字颜色 |
.strokeColor |
描边颜色 |
.strokeWith |
描边大小 |
.font |
字体: 相关字体的属性去字体里面设置,大小,字体类型等等 |
我是在一个 TableViewController
中修改 Cell
的某个 Label
,外面的代码不写了,只解释里面的关于修改字符的部分spa
// 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