HowTo —— SwiftUI2.0 如何使用 Label
SwiftUI2.0 中新增了 Label 控件,方便我们添加由图片和文字组成的标签
基本用法
Label("Hello World",systemImage:"person.badge.plus")

健康笔记 - 新生活从记录开始
健康笔记是一款智能的数据管理和分析工具,让您完全掌控自己和全家人的健康信息。作为慢性病患者,肘子深知健康管理的重要与难度。创建健康笔记的初心,就是要为您提供一款轻松高效的健康信息记录与分析工具
推荐
支持自定义标签风格
import SwiftUI
struct LabelTest: View {
var body: some View {
List(LabelItem.labels(),id:\.id){ label in
Label(label.title,systemImage:label.image)
.foregroundColor(.blue)
.labelStyle(MyLabelStyle(color:label.color))
}
}
}
struct MyLabelStyle:LabelStyle{
let color:Color
func makeBody(configuration: Self.Configuration) -> some View{
HStack{
configuration.icon //View, 不能精细控制
.font(.title)
.foregroundColor(color) //颜色是叠加上去的,并不能准确显示
configuration.title //View, 不能精细控制
.foregroundColor(.blue)
Spacer()
}.padding(.all, 10)
.background(
RoundedRectangle(cornerRadius: 10)
.fill(Color.yellow)
)
}
}
struct LabelItem:Identifiable{
let id = UUID()
let title:String
let image:String
let color:Color
static func labels() -> [LabelItem] {
return [
LabelItem(title: "Label1", image: "pencil.tip.crop.circle.badge.plus", color: .red),
LabelItem(title: "df", image: "person.crop.circle.fill.badge.plus", color: .blue),
]
}
}

使用自己的 Label 控件,更多控制力
Label 能够提高开发效率,不过并不能精细控制,下面代码使用自定义 MyLabel,可以支持 SF2.0 提供的彩色符号。
import SwiftUI
struct LabelTest: View {
@State var multiColor = true
var body: some View {
VStack{
Toggle("彩色符号", isOn: $multiColor).padding(.horizontal, 20)
List(LabelItem.labels(),id:\.id){ label in
MyLabel(title:label.title,
systemImage:label.image,
color:label.color,
multiColor:multiColor)
}
}
}
struct LabelItem:Identifiable{
let id = UUID()
let title:String
let image:String
let color:Color
static func labels() -> [LabelItem] {
return [
LabelItem(title: "Label1", image: "pencil.tip.crop.circle.badge.plus", color: .red),
LabelItem(title: "df", image: "person.crop.circle.fill.badge.plus", color: .blue),
]
}
}
struct MyLabel:View{
let title:String
let systemImage:String
let color:Color
let multiColor:Bool
var body: some View{
HStack{
Image(systemName: systemImage)
.renderingMode(multiColor ? .original : .template)
.foregroundColor(multiColor ? .clear : color)
Text(title)
.bold()
.foregroundColor(.blue)
Spacer()
}
.padding(.all, 10)
.background(
RoundedRectangle(cornerRadius: 10)
.fill(Color.yellow)
)
}
}

如果您发现本文对您有所帮助或者享受阅读,请考虑捐赠以支持我的写作。您的贡献将帮助我继续为您创造有价值的内容。
通过 微信、 Patreon、 Buy Me a Coffee 进行捐赠。
欢迎通过 Twitter、 Discord 频道 或下方的留言板与我进行交流。
通过 微信、 Patreon、 Buy Me a Coffee 进行捐赠。
欢迎通过 Twitter、 Discord 频道 或下方的留言板与我进行交流。
本博客文章采用 CC 4.0 协议,转载需注明出处和作者。