UITableViewCell
是 iOS 开发中用于显示列表项的视图组件。当用户滚动 UITableView
时,系统会根据需要重用 UITableViewCell
实例以提高性能。
当 UITableViewCell
内容在滚动后消失,通常是由于以下原因:
以下是一个示例代码,展示如何正确处理 UITableViewCell
的重用和数据绑定:
import UIKit
class MyTableViewCell: UITableViewCell {
let titleLabel = UILabel()
let subtitleLabel = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupViews() {
contentView.addSubview(titleLabel)
contentView.addSubview(subtitleLabel)
// 设置布局约束
titleLabel.translatesAutoresizingMaskIntoConstraints = false
subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4),
subtitleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
subtitleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
subtitleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8)
])
}
func configure(with title: String, subtitle: String) {
titleLabel.text = title
subtitleLabel.text = subtitle
}
}
class MyViewController: UIViewController, UITableViewDataSource {
let tableView = UITableView()
var data = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
view.addSubview(tableView)
// 设置布局约束
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! MyTableViewCell
let item = data[indexPath.row]
cell.configure(with: item, subtitle: "Subtitle for \(item)")
return cell
}
}
MyTableViewCell
包含了标签视图,并在 setupViews
方法中设置了布局约束。configure(with:)
方法用于更新单元格的内容。cellForRowAt
方法中,通过 dequeueReusableCell(withIdentifier:)
获取重用的单元格实例,并调用 configure(with:)
方法更新其内容。通过这种方式,可以确保每次单元格被重用时,其内容都能正确更新,避免内容消失的问题。
领取专属 10元无门槛券
手把手带您无忧上云