Search code examples
iosswiftswiftuiswiftui-navigationview

How to set the view on top in ios SwiftUI?


I had tried this code, I have also tried with stacks but not able to align with top . I just want the view to appear on top with auto layout as like UIKit .

import SwiftUI

struct ItemDetail: View {
    let item : MenuItem
    var body: some View {
        HStack(alignment: .top){
            VStack{
                Image(item.mainImage)
                Text(item.description)
            }
            .padding(10)
            .background(.red)
            .navigationTitle(item.name)
        }
        
    }
}

struct ItemDetail_Previews: PreviewProvider {
    static var previews: some View {
        ItemDetail(item: MenuItem.example)
    }
}

enter image description here


Solution

  • Swap the HStack for a VStack and add a Spacer() at the end. e.g.:

    struct ItemDetail: View {
        let item : MenuItem
        var body: some View {
            VStack{
                VStack{
                    Image(item.mainImage)
                    Text(item.description)
                }
                .padding(10)
                .background(.red)
                .navigationTitle(item.name)
    
                Spacer()
            }
            
        }
    }