UITableViewCell与UIStackView的不同项目



我有一个典型的带有自定义单元格的UITableView。所有单元格都属于同一类型-一个UIStackView包含相同类型的视图,但数量不同。

尝试将一个单元格用于所有单元格-删除和添加内部视图的速度很慢。

尝试为不同数量的子视图创建不同的单元格:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = rows[indexPath.row]
let CellIdentifier = "CellIdentifier(row.subrows.count)"
var cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as? CustomCell
if cell == nil {
tableView.register(UINib(nibName: "WTRemindersTableViewCell", bundle: nil), forCellReuseIdentifier: CellIdentifier)
cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as? CustomCell
for _ in row.subrows {
let v = Bundle.main.loadNibNamed("CustomInnerView", owner: self, options: nil)?.first as! WTRemindersCellLineView
cell!.stackView.addArrangedSubview(v)
}
}
return cell!
}

但它似乎只注册了一个没有子视图的单元格,并且使用不同的单元格标识符毫无意义(因为每次都需要手动添加stackview子视图(。

如何解决这个问题?

已编辑

添加了小区的代码

class CustomCell: UITableViewCell {
@IBOutlet var boxView: UIView!
@IBOutlet var imgView: UIImageView!
@IBOutlet var lblTitle: UILabel!
@IBOutlet var lblSubtitle: UILabel!
@IBOutlet var dashedView: WTDashedView!
@IBOutlet var stackView: UIStackView!

weak var delegate: CustomCellDelegate?
var index: Int!

lazy var onceDraw: () = {
boxView.layer.applySketchShadow()
}()

override func awakeFromNib() {
super.awakeFromNib()
boxView.layer.cornerRadius = 19
imgView.layer.cornerRadius = 12
}

override func draw(_ rect: CGRect) {
super.draw(rect)
_=onceDraw
}

@IBAction func btnDotsClicked(_ sender: Any) {
delegate?.btnDotsClicked(at: index)
}
}

首先,您应该在viewDidLoad中注册您的单元格。注意:我不确定你的笔尖叫什么名字,所以一定要根据你的需要进行调整。

override func viewDidLoad() {
super.viewDidLoad()
tableView.register(
UINib(nibName: "CustomCell", bundle: nil),
forCellReuseIdentifier: "CustomCell"
)
}

很难判断你在cellForRowAt方法中做了什么,但这会成功的。单元格将被重复使用,因此请确保删除所有剩余的已排列子视图。如果你这样做,你不应该有任何性能问题:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
let row = rows[indexPath.row]
cell.stackView.arrangedSubviews.forEach { $0.removeFromSuperview() }
for _ in row.subrows {
cell.stackView.addArrangedSubview(cellView())
}
return cell
}

这只是一个实例化视图的小助手方法:

func cellView() -> WTRemindersCellLineView {
return Bundle.main.loadNibNamed(
"WTRemindersCellLineView", owner: nil, options: nil
)?.first as! WTRemindersCellLineView
}

最新更新