'Overridable colors with defaults in custom SwiftUI component
I am currently building some custom components for my SwiftUI app, and wondering how to handle default but overridable UI values, such as colors or paddings, in these components. Let's take a simple example:
struct TagView: View {
let text: String
var body: some View {
Text(text)
.font(.footnote)
.fontWeight(.semibold)
.multilineTextAlignment(.center)
.padding(10.0)
.background(.gray)
.cornerRadius(4)
}
}
I would like this element to have a default background color, but to be able to override this from the outside using.background(). Unfortunately, it seems that as soon as I use .background() inside my component, any attempt to override it from the outside does nothing.
How to handle these sorts of customizations? It seems the native SwiftUI components are able to do this (for example Text() has a default foregroundColor, but you can override it).
Solution 1:[1]
Here is a demo of possible approach - define own background modifier with redefined internal default color.
Tested with Xcode 13.2 / iOS 15.2
struct TagView: View {
let text: String
private var backColor = Color.gray // << default !!
var body: some View {
Text(text)
.font(.footnote)
.fontWeight(.semibold)
.multilineTextAlignment(.center)
.padding(10.0)
.background(backColor) // << here !!
.cornerRadius(4)
}
// If needed to have own Type for chain of custom modifiers return Self
// func background(_ color: Color) -> Self {
func background(_ color: Color) -> some View { // << here !!
var view = self
view.backColor = color
return view
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Asperi |
