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
1.0k views
in Technique[技术] by (71.8m points)

ios - Screen Background Color With ScrollView And Navigation Bar 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
    //    }
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

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.

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

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.


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

...