Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

ios - How to change the background color for a Form in SwiftUI?

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)

    }
}

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Preview

Note that those top and bottom white areas are safe are and you can use .edgesIgnoringSafeArea() modifier to get rid of them.


Restore

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.

And the default colors are:

UIColor.systemGroupedBackground for the grouped style. And

UIColor.systemBackground for the plain style.

And they both have automatic support for both dark mode and light mode.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...