Introduced in iOS 15 and SwiftUI 3, foregroundStyle is a new modifier which can be used to apply color or pattern as foreground to view. This modifier can be applied to style content of text, shapes, symbols, images etc.
Let’s start by setting foreground style with orange color:
struct ForegroundStyleExample: View {
var body: some View {
VStack {
Text("DevTechie")
Image(systemName: "globe")
Capsule()
.frame(height: 50)
.overlay {
Text("SwiftUI 3")
.foregroundColor(.pink)
}
}
.font(.system(size: 42))
.foregroundStyle(Color.orange)
}
}
Another use case of this can be to apply gradient on Text view.
Note: Prior iOS 15, adding gradient effect on Text would require custom implementation. If you would like to learn about that, check out this video on YouTube(while you are there hit the like and subscribe for me 😜): https://www.youtube.com/watch?v=m_EWD6LkVls
So back to applying gradient on Text, here is how it goes:
struct ForegroundStyleExample: View {
var body: some View {
VStack {
Text("DevTechie")
Image(systemName: "globe")
Capsule()
.frame(height: 50)
.overlay {
Text("SwiftUI 3")
.foregroundColor(.white)
}
}
.font(.system(size: 42))
.foregroundStyle(
LinearGradient(
colors: [.pink, .orange],
startPoint: .top,
endPoint: .bottom)
)
.padding()
}
}
Note: if you are applying style to single Shape, use fill(style:) instead as it’s more efficient to use .fill
over .foregroundStyle
We can apply material as foregroundStyle as well:
struct ForegroundStyleExample: View {
var body: some View {
ZStack {
LinearGradient(colors: [.teal, .blue], startPoint: .leading…