Swift UILabel设置多色字体的实现方法
在Swift中使用UILabel
的attributedText
属性实现多色字体
在iOS开发中,UILabel
通常用于显示文本,但如果我们需要在同一个标签内显示多种颜色和字体,可以借助NSAttributedString
类实现。以下是具体步骤:
1. 设置文本属性
定义文本片段及其属性,例如颜色和字体大小。
let titleText = "标题"
let titleAttributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 20),
.foregroundColor: UIColor.blue
]
let bodyText = "这是正文"
let bodyAttributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 16),
.foregroundColor: UIColor.black
]
2. 组合文本片段
通过NSMutableAttributedString
将不同属性的文本片段合并:
let attributedTitle = NSAttributedString(string: titleText, attributes: titleAttributes)
let attributedBody = NSAttributedString(string: bodyText, attributes: bodyAttributes)
let combinedAttributedString = NSMutableAttributedString()
combinedAttributedString.append(attributedTitle)
combinedAttributedString.append(attributedBody)
3. 设置UILabel
的attributedText
将NSMutableAttributedString
对象赋值给UILabel
的attributedText
属性,使文本显示多种颜色和字体:
let label = UILabel()
label.attributedText = combinedAttributedString
Tip: 为满足复杂需求,可考虑自定义
UILabel
的子类,实现动态生成多色字体的功能。
项目示例:您可以查看示例项目“LabelDiffColorFont-master”以获得更多实现细节。
swift-UILabel的text设置不同颜色字体.zip
预估大小:21个文件
LabelDiffColorFont-master
文件夹
wee
文件夹
ViewController.m
2KB
Info.plist
1KB
main.m
313B
Base.lproj
文件夹
LaunchScreen.storyboard
2KB
Main.storyboard
2KB
ViewController.h
194B
AppDelegate.h
256B
39.11KB
文件大小:
评论区