HowTo —— How to Use Label in SwiftUI 2.0
SwiftUI 2.0 introduced the Label widget, making it convenient for us to add labels composed of images and text.
Basic Usage
Label("Hello World", systemImage: "person.badge.plus")
Support for Custom Label Styles
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, cannot be finely controlled
.font(.title)
.foregroundColor(color) //Color is overlaid, and cannot be displayed accurately
configuration.title //View, cannot be finely controlled
.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),
]
}
}
Using Your Own Label Widget for More Control
While Labels can improve development efficiency, they do not allow for fine control. The following code uses a custom MyLabel, which supports the colorful symbols provided by SF 2.0.
import SwiftUI
struct LabelTest: View {
@State var multiColor = true
var body: some View {
VStack {
Toggle("Colored Symbols", 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)
)
}
}