如何在 SwiftUI 中更改表单的背景颜色? [英] How to change the background color for a Form in SwiftUI?

查看:15
本文介绍了如何在 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的背景颜色.但是由于 ColorUIColor 的值略有不同,你可以去掉 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 修饰符在不同的视图中改变它(因为它是一个全局改变).因此,您可以使用另一个 onAppearonDisappear 将其重置回到您想要的状态.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆