我在 viewModel 中将模型作为数组进行管理并更改模型的属性。
我不知道为什么视图不会随着模型属性的变化而变化。
非常感谢您的建议和反馈。
这是代码:
型号
class RoutineUnit: Identifiable, Equatable {
static func == (lhs: RoutineUnit, rhs: RoutineUnit) -> Bool {
return lhs.id == rhs.id
}
let id: String
var title: String
var isSelected: Bool
var targetTask: RoutineUnitTask
var tags: [RoutineUnitTag?]
var tipComment: String
}
视图模型
class RoutineDetailViewModel: ObservableObject {
@Published var routineUnits: [RoutineUnit]
func toggleSelection(for unitID: String) {
if let index = routineUnits.firstIndex(where: { $0.id == unitID }) {
routineUnits[index].isSelected.toggle()
}
}
}
查看
struct RoutineUnitView: View {
@ObservedObject var viewModel: RoutineDetailViewModel
var unitID: String
var body: some View {
if let routineUnit = viewModel.getRoutineUnitByID(unitID) {
RoundedRectangle(cornerRadius: 10)
.fill(Color.white)
.overlay {
...
}
.frame(height: 84)
.onTapGesture {
withAnimation(.spring) {
if(viewModel.isEditingEnabled) {
viewModel.toggleSelection(for: unitID)
}
}
}
}
}
}
viewModel.toggleSelection(for: unitID)即使它显然正在运行,视图也不会重绘。也许我不懂mvvm?
看,MVVM 意味着你有 ViewModel 和 View。查看订阅 ViewModel 更新/更改。 在你的例子中:
struct ContentView: View {
@ObservedObject var viewModel = RoutineDetailViewModel()
var body: some View {
List(viewModel.routineUnits) { unit in
RoutineUnitView(unit: unit)
}
}
}
class RoutineDetailViewModel: ObservableObject {
@Published var routineUnits: [RoutineUnit] = []
init() {
routineUnits = [
.init(id: "1", isSelected: false),
.init(id: "12", isSelected: false),
.init(id: "123", isSelected: false),
.init(id: "1234", isSelected: false),
.init(id: "12345", isSelected: false),
.init(id: "123456", isSelected: false),
.init(id: "1234567", isSelected: false),
.init(id: "12345678", isSelected: false)
]
}
}
struct RoutineUnitView: View {
// if you want yo modify property inside View you should to mark it @State
@State var unit: RoutineUnit
var body: some View {
RoundedRectangle(cornerRadius: 10)
.fill(unit.isSelected ? .green :.white)
.frame(height: 84)
.overlay {
VStack {
Text($unit.id)
}
}
.onTapGesture {
withAnimation {
unit.isSelected = true
}
}
}
}
也不想注意到最好将模型创建为结构(而不是类对象)。在您的初始代码中 RoutineUnit 是 class
struct RoutineUnit: Identifiable {
var id: String
var isSelected: Bool
}
要了解有关 SwiftUI 中的 MVVM 的更多信息,您可以访问: