SwiftUI .sheet view resizing issue (testing on macos)
Asked Answered
N

1

1

I have the following sample code:

import SwiftUI

struct ContentView: View {
    @State private var showModal = false
    @State private var hmm = true
    
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, world!")
        }
        .padding()
        .sheet(isPresented: $showModal) {
            VStack {
                Button {
                    hmm.toggle()
                } label: {
                    Image(systemName: "plus")
                }
                if hmm {
                    VStack {
                        Text("Some Text")
                        Text("Some Text")
                        Text("Some Text")
                        Text("Some Text")
                        Text("Some Text")
                    }
                }
            }.padding()
        }
        .toolbar {
            Button {
                showModal = true
            } label: {
                Image(systemName: "plus")
            }
        }
    }
}

When the sheet appears, the size is correct. enter image description here When I toggle the button, the size correctly recalculates based on the UI elements that disappeared. enter image description here When I toggle again, the sizing is incorrect and does not seem to account for the newly visible items. How can I get the sheet to resize properly? enter image description here

Nidia answered 21/6, 2023 at 15:46 Comment(0)
N
5

Well, hopefully this helps someone. After hours of search, i've found this seemingly unrelated post: How to get Text width with SwiftUI?

Just like in the accepted answer of the referred post, I've added .fixedSize() to my VStack which has fixed the sheet's resizing issue.

if hmm {
    VStack {
        Text("Some Text")
        Text("Some Text")
        Text("Some Text")
        Text("Some Text")
        Text("Some Text")
    }
    .fixedSize()
}
Nidia answered 21/6, 2023 at 18:29 Comment(1)
This is the best you can do right now @NidiaOxidate

© 2022 - 2024 — McMap. All rights reserved.