Search code examples
listviewswiftuipositioning

How to position List view


I have following code in my struct View

var body: some View {
    NavigationView {
        List {
            Section("Measurements") {
                ForEach(meaHeaders, id: \.id) { measurement in
                    VStack {
                        HStack {
                            Text(measurement.name!)
                            Spacer()
                        }
                        HStack {
                            Text(measurement.desc ?? "").font(.caption)
                            Spacer()
                        }
                    }
                }.swipeActions() {
                    Button("Delete") {
                        
                    }.tint(.red)
                    Button("Edit") {
                        newMeasurement.toggle()
                    }.tint(.blue)
                }
            }
        }
    }.toolbar() {
        Button(action: {
            newMeasurement = true
        }, label: {
            Image(systemName: "plus.circle")
        }).sheet(isPresented: $newMeasurement) {
            NewMeasurement(showMe: $newMeasurement, processID: processID)
        }
    }
}

which is presented as shown on attached screenshotscreenshot I'm wondering how to push List view to the top. I tried various Spacers but none worked properly.


Solution

  • The downwards offset is due to the NavigationView. NavigationViews are horribly annoying in SwiftUI, particularly due to this effect they have. You can either remove the NavigationView entirely or remove the NavigationBar with .navigationBarHidden() to bump your view back up. Alternatively, you could offset the view with .offset(), but this may compromise some functionality.

    Unless you want the NavigationView, I would recommend getting rid of it and implementing your own navigation.

    Note: .navigationBarHidden() is a little buggy, and you may need to set the navigation title to "" for it to work.