Swift UILabel设置多色字体的实现方法

在Swift中使用UILabelattributedText属性实现多色字体

在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. 设置UILabelattributedText

NSMutableAttributedString对象赋值给UILabelattributedText属性,使文本显示多种颜色和字体:

let label = UILabel()
label.attributedText = combinedAttributedString

Tip: 为满足复杂需求,可考虑自定义UILabel的子类,实现动态生成多色字体的功能。

项目示例:您可以查看示例项目“LabelDiffColorFont-master”以获得更多实现细节。

zip
swift-UILabel的text设置不同颜色字体.zip 预估大小:21个文件
folder
LabelDiffColorFont-master 文件夹
folder
wee 文件夹
file
ViewController.m 2KB
file
Info.plist 1KB
file
main.m 313B
folder
Base.lproj 文件夹
file
LaunchScreen.storyboard 2KB
file
Main.storyboard 2KB
file
ViewController.h 194B
file
AppDelegate.h 256B
folder
Assets.xcassets 文件夹
folder
AppIcon.appiconset 文件夹
file
Contents.json 1KB
file
AppDelegate.m 2KB
folder
weeUITests 文件夹
file
Info.plist 733B
file
weeUITests.m 1KB
file
1.png 20KB
file
README.md 154B
folder
weeTests 文件夹
file
Info.plist 733B
file
weeTests.m 866B
folder
wee.xcodeproj 文件夹
folder
project.xcworkspace 文件夹
file
contents.xcworkspacedata 148B
folder
xcuserdata 文件夹
folder
cat.xcuserdatad 文件夹
file
UserInterfaceState.xcuserstate 14KB
folder
xcuserdata 文件夹
folder
cat.xcuserdatad 文件夹
folder
xcdebugger 文件夹
file
Breakpoints_v2.xcbkptlist 91B
folder
xcschemes 文件夹
file
xcschememanagement.plist 655B
file
wee.xcscheme 4KB
file
project.pbxproj 19KB
zip 文件大小:39.11KB