SwiftUI Label gives you ability to create custom styles with the help of LabelStyle protocol.
Protocol’s only requirement is to provide definition for makeBody function.
@ViewBuilder func makeBody(configuration: Self.Configuration) -> Self.Body
Configuration parameter is of type LabelStyleConfiguration, which gives access to icon and title of Label. So we have everything we need to customize our label:
struct CustomLabelStyle: LabelStyle {
let iconColor: Color
let titleColor: Color
let backgroundColor: Color
func makeBody(configuration: Configuration) -> some View {
HStack {
configuration.icon
.foregroundColor(iconColor)
configuration.title
.foregroundColor(titleColor)
.padding(.leading, 10)
.lineLimit(1)
configuration.icon
.foregroundColor(iconColor)
}
.padding(10)
.background(RoundedRectangle(cornerRadius: 10).fill(backgroundColor.opacity(0.2)))
}
}
In the code above, we are expecting three parameters and all are Color type to customize the look of our label. Inside makeBody function we will extract out icon and title from configuration object and style them. Once style is created we can use it as below:
Label("DevTechie", systemImage: "heart.fill")
.labelStyle(CustomLabelStyle(iconColor: .red, titleColor: .orange, backgroundColor: .teal))
.font(.largeTitle)
Output: