[英]Crash while dismissing a view that hasn't been edited - SwiftUI
我正在使用 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()
行時,問題就消失了。 不過,我需要那條線來駁回這個觀點。 為什么會發生這種情況,我該如何解決? 如果我的代碼一團糟,請原諒我。 謝謝!
看起來它在解雇期間嘗試更新,嘗試推遲解雇一點
DispatchQueue.main.async { // defer to next event
self.presentationMode.wrappedValue.dismiss()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.