I have a Classification class
@Model
final class Classification: Identifiable, Equatable {
var id: UUID
var image: String
var background: Int
var name: String
var hasDeleted: Bool
var notShow: Bool
init(id: UUID = UUID(), image: String, background: Int, name: String, hasDeleted: Bool = false,notShow: Bool = false ) {
self.id = id
self.image = image
self.background = background
self.name = name
self.hasDeleted = hasDeleted
self.notShow = notShow
}
static let mockData = Classification(image: "questionmark", background: 0xFF0000, name: "请选择标签", hasDeleted: false)
}
And I have a TodoItem class which hava a attribute type Classification
@Model
final class TodoItem: Identifiable {
var id: UUID
var title: String
var startTime: Date
var endTime: Date
var isCompleted: Bool
var isLog: Bool
var classification: Classification?
init(id: UUID = UUID(), title: String, startTime: Date, endTime: Date, isCompleted: Bool, isLog: Bool, classification: Classification?) {
self.id = id
self.title = title
self.startTime = startTime
self.endTime = endTime
self.isCompleted = isCompleted
self.isLog = isLog
self.classification = classification
}
// 创建 Log
convenience init(title: String, startTime: Date, endTime: Date, classification: Classification?) {
self.init(id: UUID(), title: title, startTime: startTime, endTime: endTime, isCompleted: true, isLog: true, classification: classification)
}
static let mockDataTodo = TodoItem( title: "todo测试", startTime: Date(), endTime: Date(timeIntervalSinceNow: 3000), isCompleted: false, isLog: false, classification: nil)
static let mockDataLog = TodoItem(title: "log测试", startTime: Date(timeIntervalSinceNow: -3000), endTime: Date(), classification: nil)
}
now A View show TodoItem data, B View show Classification data , A and B View in TabView. When I update Classification data in B View ,
A View will not update automatically and you must re-open the app before it will update.
// B View update data
@Environment(\.dismiss) var dismiss
@Bindable var editTagInfo: Classification
var modelContext: ModelContext
let presetColors: [Int] = [0xFF0000, 0x00FF00, 0x0000FF]
@State private var isSFPresented = false
@State private var showDeleteAlert = false
init(classificationId: PersistentIdentifier, in container: ModelContainer) {
modelContext = ModelContext(container)
modelContext.autosaveEnabled = false
editTagInfo = modelContext.model(for: classificationId) as? Classification ?? Classification.mockData
}
HStack {
ColorPicker("tag color", selection: colorValueBinding, supportsOpacity: false)
.padding(.trailing)
}
CircleButton(imageString: "checkmark", width: 35, backgroundColor: .green, imageColor: .white, ifGradient: true)
.onTapGesture {
withAnimation {
try! modelContext.save()
dismiss()
}
}