如何在SwiftUI中更改表单的背景颜色? [英] How to change the background color for a Form in SwiftUI?
问题描述
我想更改表单的浅灰色"背景色,但是似乎没有 .foregroundColor(Color.blue)
和 .background(Color.blue)
工作
I wanna change that "light gray" background color for a form, but .foregroundColor(Color.blue)
and .background(Color.blue)
does not seem to work
struct ContentView : View {
@State var value = ""
var body: some View {
Form {
Section(header: Text("First Name")) {
TextField($value)
}
Section(header: Text("Last Name")) {
TextField($value)
}
}.foregroundColor(Color.blue)
}
}
推荐答案
可行的解决方案:
所有SwiftUI的 List
都由iOS中的 UITableView
支持.因此您需要更改 tableView 的背景颜色.但是,由于 Color
和 UIColor
的值略有不同,因此您可以摆脱 UIColor
.
A Working Solution:
All SwiftUI's List
s are backed by a UITableView
in iOS. so you need to change the background color of the tableView. But since Color
and UIColor
values are slightly different, you can get rid of the UIColor
.
struct ContentView: View {
init(){
UITableView.appearance().backgroundColor = .clear
}
@State var value = ""
var body: some View {
Form {
Section(header: Text("First Name")) {
TextField("First Name", text: $value)
}
Section(header: Text("Last Name")) {
TextField("Last Name", text: $value)
}
}
.foregroundColor(Color.blue)
.background(Color.yellow)
}
}
现在,您可以使用所需的任何背景(包括所有颜色
)
Now you can use Any background (including all Color
s) you want
请注意,顶部和底部的白色区域是安全区域,您可以使用 .edgesIgnoringSafeArea()
修饰符来摆脱它们.
Note that those top and bottom white areas are safe are and you can use .edgesIgnoringSafeArea()
modifier to get rid of them.
由于 UITableView.appearance().backgroundColor
全局适用,因此可以使用 .onAppear
修饰符在不同的视图中对其进行更改(因为它是全局更改).因此,您可以使用另一个 onAppear
或 onDisappear
将其重置为所需的内容.
Since UITableView.appearance().backgroundColor
applies globally, you can use .onAppear
modifier to change it in different views (since it is a global change). So you can use another onAppear
or onDisappear
to reset it back to what you want.
默认颜色是:
UIColor.systemGroupedBackground
用于分组样式.还有
UIColor.systemBackground
用于纯风格.
它们都自动支持暗模式和亮模式.
And they both have automatic support for both dark mode and light mode.
这篇关于如何在SwiftUI中更改表单的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!