[英]TableView cells are repeating Swift
所以我正在向我的數據庫發出 GET 請求,然后將數組中的每個元素添加到 ViewModel 中,在var mainComment: Comments?
. 在我的自定義單元格中,我將我的 label 文本分配給 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
和likes
作為可選項:
struct Comments: Codable {
var id:String?
var likes:Int?
}
您需要處理一個else
案例(如果viewModel
為 nil,可能還需要一個else
案例):
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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.