问题描述中提到,在UITableView中自定义单元格不显示数据。这可能是由于以下原因导致的:
下面是一种解决方法,其中包含了代码示例:
tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "CustomCell")
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// 返回数据源中的行数
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
// 配置自定义单元格的数据
let data = dataArray[indexPath.row]
cell.titleLabel.text = data.title
cell.subtitleLabel.text = data.subtitle
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60.0 // 设置单元格的高度
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// 添加子视图和约束
addSubview(titleLabel)
addSubview(subtitleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
subtitleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 10),
titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
titleLabel.heightAnchor.constraint(equalToConstant: 20),
subtitleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 5),
subtitleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
subtitleLabel.heightAnchor.constraint(equalToConstant: 20)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
以上是一种解决方法,确保你的代码在这些方面配置正确,就可以显示自定义单元格中的数据了。