2
votes

I have two scroll views placed in a NavigationView. I want both the ScrollViews to inherit the colour as mentioned in the onAppear modifier.

However, when I navigate to the second ScrollView and go back to the first ScrollView, the first view inherits the second ScrollView colour.

struct ScrollView1: View {
    var body: some View {
        NavigationView {
            ScrollView {
                NavigationLink(destination: ScrollView2()) {
                    Text("First View").padding()
                }.frame(maxWidth: .infinity)
            }.navigationBarTitle("First")
            .onAppear {
                UIScrollView.appearance().backgroundColor = UIColor.green
            }
        }
    }
}

struct ScrollView2: View {
    var body: some View {
        ScrollView {
            Text("Second View").frame(maxWidth: .infinity)
        }
        .onAppear {
            UIScrollView.appearance().backgroundColor = UIColor.gray
        }
    }
}

Does anyone know how my first ScrollView will always inherit green and second, gray colour?

Adding ScrollView colour by wrapping inside a ZStack will not collapse NavigationBar from large to inline while scrolling.

Is there any other solution to achieve both i.e, preserving the navigationBar bounce behaviour along with ScrollView colour.

1

1 Answers

0
votes

First you can remove backgroundColor from UITableView and UIScrollView (you can do this in SceneDelegate, so it will only be executed once):

UITableView.appearance().backgroundColor = UIColor.clear
UIScrollView.appearance().backgroundColor = UIColor.clear

Then use ZStack to add background colours:

struct ScrollView1: View {
    var body: some View {
        NavigationView {
            ZStack {
                Color.green
                ScrollView {
                    NavigationLink(destination: ScrollView2()) {
                        Text("First View").padding()
                    }.frame(maxWidth: .infinity)
                }.navigationBarTitle("asdasd")
            }
        }
    }
}
struct ScrollView2: View {
    var body: some View {
        ZStack {
            Color.gray
            ScrollView {
                Text("Second View").frame(maxWidth: .infinity)
            }
        }
    }
}