Search code examples
swiftuinavigationbarnavigationview

SwiftUI NavigationView layout issues


My NavigationView and Title when using SwiftUI never appear where I'd expect them to appear when run on a device or simulator. I want them to be pretty much under the back button that is top left but when run on a device or simulator it goes quite far down the page, here is a screenshot of my simulator resized beside the preview and you can see how different this is.

Navigation not looking as expected

Here is my code:

import SwiftUI

struct DetailView: View {
    let tarot: Tarot
    var body: some View {
        NavigationView {
            VStack() {
                Image(tarot.tarotImage)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 200, height: 200)
                    .padding(.init(top: 80, leading: 30, bottom: 80, trailing: 30))
                Text(tarot.tarotDescription)
                    .padding(.horizontal)
            }
            .navigationBarTitle(tarot.tarotName, displayMode: .automatic)
        }
    }
}

struct DetailView_Previews: PreviewProvider {
    static var previews: some View {
        DetailView(tarot: cardsArray[0])
    }
}

Solution

  • You shouldn't have more than one NavigationView in your navigation stack.

    Try to remove the NavigationView from your DetailView:

    struct DetailView: View {
        let tarot: Tarot
        var body: some View {
            VStack {
                Image(tarot.tarotImage)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 200, height: 200)
                    .padding(.init(top: 80, leading: 30, bottom: 80, trailing: 30))
                Text(tarot.tarotDescription)
                    .padding(.horizontal)
            }
            .navigationBarTitle(tarot.tarotName, displayMode: .automatic)
        }
    }