swiftuiconstraints

Swift UI - setting View for both iPad and iPhone


I am new to using Swift UI and am coding a simple app to learn. I want the views to look the same on iPad as they do on iPhone, however the iPad shows a blank screen where the view just out of bounds. I've tried to use GeometryReader as follows in an attempt to fix:

var body: some View {
        NavigationView {
            GeometryReader { bounds in
                VStack(alignment: .center){
                    Text("Welcome to Fair Rent")
                        .font(Font.system(size: 30, design: .rounded))
                        .fontWeight(.bold)
                        .frame(width: nil)
                    Image(systemName: "person.3.fill")
                        .font(.largeTitle)
                        .padding(2)
                    Text("How many people do you live with?")
                        .font(Font.system(size:20, design: .rounded))
                        .multilineTextAlignment(.center)
                        .lineLimit(nil)
                        .padding(18.0)
                    NavigationLink(destination: FairRentView(viewModel: FairRentViewModel(Amounts(), housemates: 1)))
                    {
                        Text("      1 other person")
                            .styledLinkLabel(with: gradient)
                    }
                    NavigationLink(destination: FairRentView(viewModel: FairRentViewModel(Amounts(), housemates: 2)))
                    {
                        Text("      2 other people")
                            .styledLinkLabel(with: gradient)
                    }
                    NavigationLink(destination: FairRentView(viewModel: FairRentViewModel(Amounts(), housemates: 3)))
                    {
                        Text("      3 other people")
                            .styledLinkLabel(with: gradient)
                    }
                }
                .frame(width: bounds.size.width, height: bounds.size.height)
            }.navigationBarTitle("Fair Rent", displayMode: .inline)
        }
    }

Can someone please point me in the right direction of how to do this properly in Swift UI? Thanks


Solution

  • Use NavigationViewStyle

    struct ContentView: View {
        var body: some View {
            NavigationView {
                NavigationLink(destination: DetailView()) {
                    Text("Tap Me")
                }.navigationBarTitle(Text("ContentView"))
                    Text("Hello, I'm a Detail View")
            }.navigationViewStyle(StackNavigationViewStyle()) 
        }
    }
    
    struct DetailView: View {
        var body: some View {
            Text("Hello, I'm a Detail View")
        }
    }
    

    iPad:

    enter image description here

    iPhone:

    enter image description here