带有 ScrollView 和导航栏 SwiftUI 的屏幕背景颜色

Ric*_*oon 10 colors ios swift swiftui

我在使用带有 SwiftUI 的滚动视图时尝试使用彩色背景,但这会导致导航标题不再折叠。我已经尝试了多种方法,但这始终是一个问题。

struct Person : Identifiable{
    var id : Int
    var name : String
}

struct ContentView: View {
    let people = [
        Person(id: 1, name: "Ricky"),
        Person(id: 2, name: "Dani"),
        Person(id: 3, name: "Mark"),
        Person(id: 4, name: "Kailin"),
        Person(id: 5, name: "James"),
        Person(id: 5, name: "Jenna")
    ]

    var body: some View {
        NavigationView{
            ZStack{
                Color.red
                    .edgesIgnoringSafeArea(.all)
                ScrollView{
                    ForEach(people, id: \.id) { person in
                        Text(person.name)
                            .frame(width: 300, height: 400)
                            .background(Color.blue)
                            .padding()
                    }
                }.navigationBarTitle("Home")
            }
        }
    }

    //    init(){
    //        UIView.appearance().backgroundColor = .orange
    //    }
}
Run Code Online (Sandbox Code Playgroud)

Moj*_*ini 9

像这样重新排列您的视图:

var body: some View {
    NavigationView {

        ScrollView {
            ZStack {
                Color.red
                VStack {
                    ForEach(people, id: \.id) { person in
                        Text(person.name)
                            .frame(width: 300, height: 400)
                            .background(Color.blue)
                            .padding()
                    }
                }
            }
        }.navigationBarTitle("Home")
    }
Run Code Online (Sandbox Code Playgroud)

请注意,您可以UINavigationBar.appearance().backgroundColor = .red与另一个UIColor类似Color(UIColor.red)的背景一起使用来模拟透明大,NavigationBar直到用于在 SwiftUI 中更改正确颜色的直接 API 到来。

注意 UIColor.redColor.red.

另请注意,如果您想使用 aList而不是ScrollView,则应添加.listRowInsets(EdgeInsets())toZStack以去除多余的空格。

  • 忽略边缘在这里也不起作用。所以滚动视图的顶部和底部仍然是白色的。这并不能解决问题。不知道为什么在 swiftUI 中设置背景颜色这么难 (2认同)