Search code examples
iosswiftswiftuiscrollviewbackground-color

Change Background Color of ScrollView SwiftUI


I am new to developing IOS apps and I am having problems with extra whitespace at the bottom of my login page depending on the size of the image that I have on the screen. I have been told that I should change the background color of my ScrollView and set my view's background as clear. I am not sure about how to change the background color of the ScrollView. My code basically looks like this with some stuff removed for readability:

var body: some View {
    ScrollView {
        //if login.isLoggedIn {
        MainView()
        //} else {
        VStack() {
            
        }
        
        .background(LinearGradient(gradient: Gradient(colors: [Color{.lightblue), Color(.blue)]), startPoint: .top, endPoint: .bottom))
            .edgesIgnoringSafeArea(.all)
        }
        }
}
//}
Screen with Whitespace Screen without Whitespace After Image on Screen is Made Larger

Can someone show me how to change the background color? I would prefer the background color to be that of the linear gradient above. If not, can you show how to do this in UIScrollView?


Solution

  • Try moving the background colour setting one line below. Also this post might be helpful.

    struct ContentView: View {
        var body: some View {
            ScrollView {
                //if login.isLoggedIn {
                MainView()
                //} else {
                VStack() {
                    
                }
            }.background(
                LinearGradient(gradient: Gradient(colors: [Color(.lightblue), Color(.blue)]), startPoint: .top, endPoint: .bottom)
            ).edgesIgnoringSafeArea(.all)
        }
    }
    
    ...
    
    // Extension for custom colour lightBlue
    extension UIColor {
        static let lightBlue = UIColor(red: 0.2, green: 0.6, blue: 0.8, alpha: 1)
    }