且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在SwiftUI中更改表单的背景颜色?

更新时间:2023-09-06 14:03:58

可行的解决方案:

所有SwiftUI的 List 都由iOS中的 UITableView 支持.因此您需要更改 tableView 的背景颜色.但是,由于 Color UIColor 的值略有不同,因此您可以摆脱 UIColor .

A Working Solution:

All SwiftUI's Lists are backed by a UITableViewin 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 Colors) 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.