There are places in your code where you just need a color. But in other places, like shapes, you want to fill the entire background with a color. Swift has made the Color
class conform to the ShapeStyle
protocols. So it's natural to give a Circle()
shape a teal background like this.
// Give the circle a teal background.
// Note! You are giving the background a ShapeStyle, not a 'color'
Circle().background(.teal)
If you When you go all PRO and hire graphic artists for your applications, they'll want you to use company colors and insist you stay on brand. To make coding easier for you, you'll want to have convenience vars
to address these special colors.
However, as @twostraws points out, not everthing takes a Color
object. Sometimes, it requires a ShapeStyle
object. His goal was to have you take another step UP the LADDER, and see more of SwiftUI's glorius innards and entrails.
Paste into Playgrounds
// Extending ShapeStyle vs Extending Color
// For Vince @vtabmow
// By: Obelix, 2022.01.29
import SwiftUI
import PlaygroundSupport
struct ShapeStyleTest: View {
var body: some View {
VStack {
// These work because VStack accepts colors as Views
Color.darkBackground
Color.vinceBackground
// These work because the .background() modifier
// accepts ShapeStyles as backgrounds
Circle().background(Color.vinceBackground) // Color conforms to ShapeStyle
Circle().background(.teal)
// This does NOT WORK.
// Compiler does not know what .vinceBackground is?
// Error: Type 'ShapeStyle' has no member 'vinceBackground'
Circle().background(.vinceBackground)
}
.frame(height: 370)
}
}
extension Color {
// Extend Color class with a new vince color!
// When you find the error, cut and paste this color to the ShapeStyle extension
static var vinceBackground: Color { Color( red: 0.74, green: 0.01, blue: 0.98) }
}
extension ShapeStyle where Self == Color {
static var darkBackground: Color { Color(red: 0.1, green: 0.1, blue: 0.2) }
}
PlaygroundPage.current.setLiveView(ShapeStyleTest().frame(width: 300, height: 400))