【发布时间】:2021-06-13 08:26:07
【问题描述】:
在来回滚动之后,我知道如何保存我们对 UITableView 所做的操作。
现在我在 MVVM 上做一个简单的UITableView
其中有一个关注按钮 . 像这样。
点击后跟随按钮变为取消关注,滚动后重置。
在哪里以及如何添加代码来防止这种情况发生?
这是表格视图代码
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Vm.personFollowingTableViewViewModel.count
}
var selectedIndexArray:[Int] = []
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: FollowList_MVVM.PersonFollowingTableViewCell.identifier , for: indexPath) as? PersonFollowingTableViewCell else{
return UITableViewCell()
}
cell.configure(with: Vm.personFollowingTableViewViewModel[indexPath.row])
cell.delegate = self
return cell
}
和configure(with: )函数
@objc public func didTapButton(){
let defaultPerson = Person(name: "default", username: "default", currentFollowing: true, image: nil)
let currentFollowing = !(person?.currentFollowing ?? false)
person?.currentFollowing = currentFollowing
delegate?.PersonFollowingTableViewCell(self, didTapWith: person ?? defaultPerson )
configure(with: person ?? defaultPerson)
}
func configure(with person1 : Person){
self.person = person1
nameLabel.text = person1.name
usernameLabel.text = person1.username
userImageview.image = person1.image
if person1.currentFollowing{
//Code to change button UI
}
使用Person 类型的自定义委托
【问题讨论】:
-
如果您真的在使用 MVVM,那么您的视图模型应该包含您的模型对象(Person)而不是您的单元格
-
@JoakimDanielson 你能详细说明一下吗?在 ViewModel 中,我只有一些基于模型的硬编码数据
-
当你更新了一个人时,你至少需要告诉视图模型,保存数据的是视图模型,而不是单元格。单元格中的 Person 对象应仅被视为原始数据的副本,如前所述,原始数据位于视图模型中。
-
@JoakimDanielson 谢谢。我对此做了更多参考,并用我自己的答案进行了更新
标签: ios swift uitableview mvvm uitableviewrowaction