问题
I had a problem when following Raywenderlich Tutorial. The form view will automatically jump upward a little bit every time i clicked an item. Is this a bug? Is there anyway to solve it? The code is below. And in Contentview, i used a GroupedListStyle() to list all the items. My xcode version is 11.2, Swift 5.
Below is TaskEditingView.swift
import SwiftUI
struct TaskEditingView: View {
@Binding var task: Task
var body: some View {
Form {
TextField("Name", text:$task.name)
Toggle("Completed", isOn: $task.completed)
}
}
}
struct TaskEditingView_Previews: PreviewProvider {
static var previews: some View {
TaskEditingView(task: .constant(Task(name: "TO DO")))
}
}
Below is ContentView.swift
import SwiftUI
struct ContentView: View {
@ObservedObject var taskStore: TaskStore
@State var modalIsPresented = false
var body: some View {
NavigationView {
List {
ForEach(taskStore.tasks) { index in
RowView(task: self.$taskStore.tasks[index])
}
.onMove { sourceIndices, destinationIndex in
self.taskStore.tasks.move(
fromOffsets: sourceIndices,
toOffset: destinationIndex
)
}
.onDelete { indexSet in
self.taskStore.tasks.remove(atOffsets: indexSet)
}
}
.navigationBarTitle("Tasks")
.navigationBarItems(
leading: EditButton(),
trailing:
Button(
action: { self.modalIsPresented = true }
) {
Image(systemName: "plus")
}
)
}
.sheet(isPresented: $modalIsPresented) {
NewTaskView(taskStore: self.taskStore)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView( taskStore: TaskStore() )
}
}
Below is RowView.swift
import SwiftUI
struct RowView: View {
@Binding var task: Task
let checkmark = Image(systemName: "checkmark")
var body: some View {
NavigationLink(
destination: TaskEditingView(task: $task)
) {
if task.completed {
checkmark
} else {
checkmark.hidden()
}
Text(task.name)
.strikethrough(task.completed)
}
}
}
struct RowView_Previews: PreviewProvider {
static var previews: some View {
RowView(
task: .constant( Task(name: "To Do") )
)
}
}
ContentView.swift -> RowView.swift -> TaskEditingView.swift
回答1:
If you use a Section Inside of a form, the jumping bug is gone. If you use empty header and footer of a section, it should be look like you do it.
Form{
Section(header: Text(""), footer: Text(""), content: {
Text(...)
Toggle(...)
})
}
回答2:
Workaround
By my findings it looks like Form
layout issue, thus as a temporary solution the following workaround someone might find applicable:
Form {
TextField("Name", text:$task.name)
Toggle("Completed", isOn: $task.completed)
}
.navigationBarTitle("", displayMode: .inline) // !!!
来源:https://stackoverflow.com/questions/59242504/swiftui-form-view-jump-up-bug