ios - TableView 单元格重复 Swift
问题描述
所以我向我的数据库发出 GET 请求,然后将数组中的每个元素添加到 ViewModel 中,在var mainComment: Comments?
. 在我的自定义单元格中,我将标签文本分配给 ViewModel 的mainComment.likes
. 我应该只为我的一个单元格获得一个赞,但一个赞却为多个单元格重复。
https://giphy.com/gifs/L2U6FALmxWx981nO44
struct Comments: Codable {
var id:String?
var likes:Int?
}
import UIKit
import Foundation
class CommentViewModel {
var mainComment: Comments?
}
//CommentVC
var comments:[CommentViewModel] = []
func loadComments(completion:@escaping(()->())) {
guard let post_id = post_id else {
return
}
let getComments = GETComments(id: post_id, path: "comments")
getComments.getAllById { comments in
self.comments = comments.map { comment in
let ret = CommentViewModel()
ret.mainComment = comment
return ret
}
self.myTableView.reloadData()
completion()
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath) as! CommentCell
let item = comments[indexPath.item]
cell.viewModel = item
return cell
}
class CommentCell {
var viewModel: CommentViewModel? {
didSet {
if let item = viewModel {
if let numberOfLikes = item.mainComment?.likes {
self.numberOfLikes.text = "\(numberOfLikes)"
}
}
}
lazy var numberOfLikes:UILabel = {
let label = UILabel()
label.textAlignment = .center
label.text = "0"
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
addSubview(numberOfLikes)
commentLikesConstraints()
}
func commentLikesConstraints() {
numberOfLikes.translatesAutoresizingMaskIntoConstraints = false
numberOfLikes.widthAnchor.constraint(equalToConstant: 60).isActive = true
numberOfLikes.heightAnchor.constraint(equalToConstant: 30).isActive = true
numberOfLikes.centerXAnchor.constraint(equalTo: likeBtn.centerXAnchor).isActive = true
numberOfLikes.topAnchor.constraint(equalTo: likeBtn.bottomAnchor, constant: -5).isActive = true
}
解决方案
由于您使用mainComment
andlikes
作为选项:
struct Comments: Codable {
var id:String?
var likes:Int?
}
您需要处理一个案例(如果为 nil else
,可能还需要一个案例):else
viewModel
var viewModel: CommentViewModel? {
didSet {
if let item = viewModel {
if let numberOfLikes = item.mainComment?.likes {
self.numberOfLikes.text = "\(numberOfLikes)"
} else {
self.numberOfLikes.text = "0"
}
} else {
// do what you need to do if viewModel is nil
}
}
}
推荐阅读
- menu - 如何包装一个空的子菜单?
- java - 即使网络是由 android 上的其他设备创建的,如何删除特定网络?
- c++ - 两个 timeval 结构的 tv_sec 怎么可能相同,但减去它们会给我一个非零值
- powerbi - 应用于 DAX 中的虚拟表和计算表时,与 sumx 函数的结果不同
- laravel - 指定冗余 API 端点的优缺点是什么?
- java - 如何将 watermill 中的解组器(Kafka 的 lib)更改为 avro
- java - 当 screenOrientation 固定时获取旋转信息(Android、JAVA)
- python - 推迟变量初始化直到评估
- javascript - 为什么数组长度为零?
- python - 在 Python 中按函数输出压缩列表