如何为SwiftUI配置提供默认值,但让用户覆盖它们



我创建了一个SwiftUI图表,并使用了一个字典来保存视图中使用的颜色:

let ChartColors: [String: Color] = [
"title": Color.white,
"timeAgo": Color.red,
...
]

在我的structbody变量中,我可以使用以下内容:

struct Chart: View {

var body: some View {

Text("5min ago")
.foregroundColor(ChartColors["timeAgo"])

}
}

让我在父视图中自定义这些字典值,同时在图表视图中保留这些默认值的最佳方式是什么,以防我不想更改它们?

您可以为您的颜色创建一个结构(并提供默认值(:

struct ChartColors {
var title = Color.white
var timeAgo = Color.red
}

然后在您的视图中使用它:

struct ContentView: View {
var body: some View {
let chartColors = ChartColors(title: .black, timeAgo: .green)
return VStack {
Chart(chartColors: chartColors) // with overridden colors
Chart() // with default colors
}
}
}
struct Chart: View {
var chartColors = ChartColors()
var body: some View {
Text("5min ago")
.foregroundColor(chartColors.timeAgo)
}
}

最新更新