SwiftUI LabelStyle
SwiftUI allows to implement custom `LabelStyle`s, which makes it easy to format multiple `Label`s in the same way. To apply a LabelStyle the modifier `.labelStyle()` is used.
LabelStyles are implemented by conforming to the `LabelStyle` protocol and implementing the function `func makeBody(configuration: Configuration) -> some View`. In the sample code the icon image has a circular background and the whole label has a capsule background.
import SwiftUI
struct SampleLabelStyleView: View {
var body: some View {
VStack(spacing: 16, content: {
Text("LabelStyle")
.font(Font.largeTitle)
VStack {
Spacer()
Label("Monday", systemImage: "sun.max")
.labelStyle(DayLabelStyle())
Label("Tuesday", systemImage: "cloud.sun")
.labelStyle(DayLabelStyle())
Label("Wednesday", systemImage: "sun.haze")
.labelStyle(DayLabelStyle())
Label("Thursday", systemImage: "cloud.rain")
.labelStyle(DayLabelStyle())
Label("Friday", systemImage: "sun.haze")
.labelStyle(DayLabelStyle())
Label("Saturday", systemImage: "sun.max")
.labelStyle(DayLabelStyle())
Label("Sunday", systemImage: "sun.max")
.labelStyle(DayLabelStyle())
Spacer()
}
.fixedSize(horizontal: true, vertical: false)
})
}
struct DayLabelStyle: LabelStyle {
func makeBody(configuration: Configuration) -> some View {
HStack(spacing: 16) {
configuration.icon
.foregroundStyle(Color.blue)
.padding(8)
.background {
Circle().fill(Color.white)
}
configuration.title
.foregroundStyle(Color.blue)
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding()
.background {
Capsule().fill(Color.blue.opacity(0.07))
}
}
}
}
#Preview {
SampleLabelStyleView()
}