带有 ScrollView 和导航栏 SwiftUI 的屏幕背景颜色 [英] Screen Background Color With ScrollView And Navigation Bar SwiftUI

查看:22
本文介绍了带有 ScrollView 和导航栏 SwiftUI 的屏幕背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im trying to have a colored background while using a scrollview with SwiftUI but this causes the navigation title to no longer collapse. I've tried a number of ways yet this is always an issue.

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
    //    }
}

推荐答案

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

Rearrange your views like this:

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")
    }

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

NOTE THAT You can use UINavigationBar.appearance().backgroundColor = .red alongside with another UIColor like Color(UIColor.red) for the background to simulate the transparent large NavigationBar until the direct API for changing the proper colors in SwiftUI arrives.

并且注意 UIColor.redColor.red 略有不同.

And NOTE THAT UIColor.red is slightly different with Color.red.

另外注意如果你想使用List而不是ScrollView,你应该添加.listRowInsets(EdgeInsets())ZStack 以去除多余的空格.

Also NOTE THAT if you want to use a List instead of ScrollView, you should add .listRowInsets(EdgeInsets()) to ZStack to get rid of the extra white space.

这篇关于带有 ScrollView 和导航栏 SwiftUI 的屏幕背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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