【发布时间】:2021-08-20 20:32:07
【问题描述】:
如何更新列表中现有行的内容?
print语句显示按钮正在更新Bool,但View没有更新。
内容(按钮)按预期移动,但动作和格式没有按预期改变。
我正在使用的页面的代码:
struct NotificationView: View {
@ObservedObject var notificationVModel: NotificationVModel = NotificationVModel()
var body: some View {
NavigationView{
List(notificationVModel.notificationarray,id:\.NotificationName){notificationVV in
ZStack {
if notificationVV.isShgowen {
Color (.green).opacity(0.1)
.cornerRadius(10)
}
HStack{
Button(action: {
notificationVV.changTogle()
print("\(notificationVV.isShgowen)")
}, label: {
ZStack{
Circle()
.foregroundColor(Color(red: 0 / 255, green: 175 / 255, blue: 80 / 255))
.frame(width: 50, height: 50, alignment: .center)
Image(systemName: "bell")
.frame(width: 40, height: 40, alignment: .center)
.foregroundColor(.white)
} })
VStack{
HStack {
if notificationVV.isShgowen{
Text("true")
.font(.custom("AvenirNext-DemiBold", size: 10))
}
Text(notificationVV.NotificationName)
.font(.custom("AvenirNext-DemiBold", size: 20))
Spacer()
Text(notificationVV.NotifivationDate)
.font(.custom("AvenirNext-Medium", size: 12))
.foregroundColor(.gray)
}.padding(.leading).padding(.trailing)
Text(notificationVV.NotificationDiscrip)
.font(.custom("AvenirNext-Regular", size: 11))
.lineLimit(nil)
.padding(.leading).padding(.trailing)
}
}.padding()
}
}
.navigationTitle("Notification")
.navigationBarTitleDisplayMode(.inline)
}
}
}
视图模型
class NotificationVModel: ObservableObject {
@Published var notificationarray : [NotificationV] = [
NotificationV(NotificationName: "Notification 1", NotificationDiscrip: "Lorem ipsum dolor sit amet,consec tetur adipiscing elit Lorem ipsum doloramet,consec tetur adipiscing elit sit ipi piscing… ", NotifivationDate: "04/02/2021", isShgowen: false), NotificationV(NotificationName: "Notification 2", NotificationDiscrip: "Lorem ipsum dolor sit amet,consec tetur adipiscing elit Lorem ipsum doloramet,consec tetur adipiscing elit sit ipi piscing… ", NotifivationDate: "05/03/2021", isShgowen: true),
]
}
型号
class NotificationV : ObservableObject{
let objectWillChange = ObservableObjectPublisher()
@Published var NotificationName : String = ""
@Published var NotificationDiscrip: String = ""
@Published var NotifivationDate:String = ""
@Published var isShgowen:Bool = false
init(NotificationName: String, NotificationDiscrip: String, NotifivationDate: String, isShgowen: Bool) {
self.NotificationName = NotificationName
self.NotificationDiscrip = NotificationDiscrip
self.NotifivationDate = NotifivationDate
self.isShgowen = isShgowen
}
func changTogle(){
if isShgowen == false {
isShgowen = true
}
}
}
【问题讨论】:
-
您正在发布一个数组,所以我的猜测是视图对数组的更改做出反应,但对数组中元素的更改没有反应。
-
NotificationV 是类还是结构?
-
NotificationV 是类
-
你的模型(NotificationV)应该是结构体。
-
当我把它改造成编译器时给我一个错误(不能分配给属性:'notificationVV'是一个'let'常量)