简体   繁体   中英

SwiftUI: Initial list element's position is wrong

Im new to Swift and I have a question regarding the list view.

The code below creates a List of an image as a button followed by a text.

The problem is that the List elements are initially slightly left, but they move to the right into place when they're first updated.

import SwiftUI

struct TodoItem {
    var name: String
    var completed: Bool

    init(_ name: String) {
        self.name = name
        self.completed = false
    }
}

struct ContentView: View {

    @State var todos: [TodoItem] = [
        TodoItem("This"),
        TodoItem("Is"),
        TodoItem("Some"),
        TodoItem("Todo"),
        TodoItem("Task")
    ]

    var body: some View {
        NavigationView {
            List(todos.indices) { index in
                HStack {
                    Image(systemName: self.todos[index].completed ? "checkmark.circle" : "circle")
                        .imageScale(.large)
                        .onTapGesture {
                            self.todos[index].completed.toggle()
                        }

                    Text(self.todos[index].name)
                    Spacer()
                }
            }
            .navigationBarTitle("Todos")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Here is fixed body (tested & works with Xcode 11.3.1)

var body: some View {
    NavigationView {
        List {
            ForEach (todos.indices) { index in
                HStack {
                    Image(systemName: self.todos[index].completed ? "checkmark.circle" : "circle")
                        .imageScale(.large)
                        .onTapGesture {
                            self.todos[index].completed.toggle()
                        }

                    Text(self.todos[index].name)
                    Spacer()
                }
            }.listRowInsets(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20))
        }
        .navigationBarTitle("Todos")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM