Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop SwiftUI view from getting wider than superview

I created a UIHostingController to put a SwiftUI view in my app. The root view contains a VStack, and inside that some HStacks and Pickers. The picker pushes the view wider than the screen by 8 points. It looks bad - text is slightly off screen. Usually I would fix this with auto layout constraints that pin the left and right edges of the view to the superview, with priority 1000 (required). What is the equivalent in SwiftUI?

Some boiled down code that triggers the problem

struct EditSegmentView: View {

    @State var seconds: Int = 10

    var body: some View {
        VStack {
            HStack {
                Text("Pause after intro")
                Spacer()
                Text("10 seconds")
            }
            Picker(selection: $seconds, label: Text("Seconds")) {
                ForEach(0..<60) { n in
                    Text("\(n) sec").tag(n)
                }
            }
        }
    }
}

That is displayed from a UIViewController, like this:

let editView = EditSegmentView()
let vc = UIHostingController(rootView: editView)
vc.modalPresentationStyle = .fullScreen
present(vc, animated: true)
like image 316
Rob N Avatar asked Nov 16 '25 15:11

Rob N


2 Answers

I can't see anything obviously wrong with the code provided. You could try using a GeometryReader to force the VStack to be the width of the available space. Also add some padding(), because otherwise your Text will start right at the edge

var body: some View {
    GeometryReader { proxy in
        VStack {
            //...
        }   .padding()
            .frame(width: proxy.size.width)
    }
}

Are there any clues as to why the view is expanding beyond the edges when you debug its view hierarchy?

like image 133
LuLuGaGa Avatar answered Nov 18 '25 08:11

LuLuGaGa


This is a little late, but I had the same issue and fixed by making sure the outer VStack had it's alignment set to .leading. The inner Vstack also has alignment: leading and then added a .padding() to the inner VStack

like image 34
Jesse Naugher Avatar answered Nov 18 '25 08:11

Jesse Naugher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!