SwiftUI - can I make one element in Form fill the whole screen width (without horizontal margins)?

1.5k Views Asked by At

I would like a single item inside SwiftUI Form to run from side to side, without having Form's default margins.

Unfortunately, whatever I do (like ading a wider .frame, negative horizontal padding, or .offset), the team image view seems to be always cropped by the form to fit the form area (= has horizontal margins).

Is it possible to make the Image below touch the left and right side of the screen?

I am using Form for my app settings, but I would like to add a full-width section there (think eg. a banner to promote a feature).

SwiftUI Playgrounds code:

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    var body: some View {
        Form {
            Section(
                header: Text("First section")
            ) {
                Text("Hello world")
            }
            
            Text("The image below should be stretched to touch the left and right window edge, without being cropped by the Form.")
            Image(systemName: "sun.max.fill")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .listRowInsets(EdgeInsets()) // this is supposed to fix the problem, but all it does is to set the default item inner padding to zero, so the image at least touches the edge of teal area.
                .listRowBackground(Color.teal)
            
            Section(
                header: Text("Last section")
            ) {
                Text("Hello world")
            }
        }
    }
}

PlaygroundPage.current.setLiveView(ContentView())

How it looks: swiftui form - not wide enough

1

There are 1 best solutions below

1
Jacob Bartlett On

Unfortunately, SwiftUI Form is very temperamental and forces you to strictly adhere to the standard iOS Settings screen formatting.

Fortunately, you can re-implement similar formatting yourself with SwiftUI!

For the top, something like:

VStack(spacing: 4) {
        Text("FIRST SECTION")
            .font(.system(size: 12, weight: .regular))
            .foregroundColor(.gray)
            .padding(.leading)
        
        Text("Hello, world!")
            .font(.system(size: 15, weight: .regular))
            .foregroundColor(.black)
            .padding(.horizontal)
            .frame(height: 44, alignment: .center)
            .background(Color.white)
            .cornerRadius(10)
    }