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

1

3

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

Oxendine answered 19/5, 2022 at 10:47 Comment(0)
N
0

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)
    }
Nominate answered 19/5, 2022 at 11:53 Comment(1)
Thank you, I would prefer to not reimplement Form, as it has a lot of nontrivial behaviors (like adaptive width depending on window size etc.) - if it wouldn't be possible to do this without reiplmeneting the form, I'll rather fit the design into the constraint ...Impedance

© 2022 - 2024 — McMap. All rights reserved.