如何解决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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。