我正在使用SwiftUI构建iOS应用。当我单击“完成”按钮,并且entry
属性不是nil
,并且我没有使用DatePicker
TextField
或TextView
时,我得到AppDelegate
中的以下运行时错误:
线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x7ffee2a83fe8)
这是我的代码:
import SwiftUI
struct EditView: View {
@State var entry: Entry?
@ObservedObject var entries: Entries
@State var newDate: Date
@State var newTitle: String
@State var newBody: String
@Environment(\.presentationMode) var presentationMode
init(entries: Entries, entry: Entry?) {
UIScrollView.appearance().keyboardDismissMode = .onDrag
_entry = .init(initialValue: entry)
_entries = .init(initialValue: entries)
_newDate = .init(initialValue: entry?.date ?? Date())
_newTitle = .init(initialValue: entry?.title ?? "")
_newBody = .init(initialValue: entry?.body ?? "")
}
var body: some View {
GeometryReader { geometry in
Form {
Section {
DatePicker("Date", selection: self.$newDate, in: ...Date(), displayedComponents: .date)
.labelsHidden()
}
Section {
TextField("Title (optional)", text: self.$newTitle)
TextView(placeholder: "Entry", text: self.$newBody)
.frame(width: geometry.size.width, height: 250, alignment: .topLeading)
}
}
}
.navigationBarItems(trailing:
Button("Done") {
if let entry = self.entry {
if let index = self.entries.list.firstIndex(of: entry) {
self.entries.list[index] = Entry(date: self.newDate, title: self.newTitle, body: self.newBody)
}
} else {
self.entries.list.append(Entry(date: self.newDate, title: self.newTitle, body: self.newBody))
}
self.presentationMode.wrappedValue.dismiss()
})
}
}
import Foundation
class Entries: ObservableObject {
@Published var list = [Entry]()
}
class Entry: ObservableObject, Identifiable, Equatable {
static func == (lhs: Entry, rhs: Entry) -> Bool {
return lhs.id == rhs.id
}
let id = UUID()
@Published var date: Date
var dateString: String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
return formatter.string(from: self.date)
}
@Published var title: String
@Published var body: String
init(date: Date, title: String, body: String) {
self.date = date
self.title = title
self.body = body
}
static let example = Entry(date: Date(), title: "I wrote some swift today", body: "Today I wrote some swift for an app I'm developing. It was very fun.")
当我删除self.presentationMode.wrappedValue.dismiss()
行时,问题就消失了。虽然,我需要那条线来消除观点。为什么会发生这种情况,我该如何解决?如果我的代码完全混乱,请原谅我。谢谢!
答案 0 :(得分:0)
在关闭过程中它似乎尝试更新,尝试推迟一点关闭过程
DispatchQueue.main.async { // defer to next event
self.presentationMode.wrappedValue.dismiss()
}