我正在尝试为我的 UITableView 创建一个自定义单元格,但是无论我是使用带有 Storyboard标识符的单元格,还是完全创建我自己的单元格,由于某种原因数据加载但它只有 1 个单元格当我滚动时。它一次只显示 1 个单元格。这是我目前正在尝试的方式:
let cell = UITableViewCell()
let cellTextLabel = UILabel()
let cellDetailLabel = UILabel()
let imageView = UIImageView()
let phImage = UIImage(named: "CryptiXJustX")
func configureCustomCell() {
cell.addSubview(imageView)
imageView.backgroundColor = .clear
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.widthAnchor.constraint(equalToConstant: 80).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 80).isActive = true
imageView.leftAnchor.constraint(equalTo: cell.leftAnchor, constant: 10).isActive = true
imageView.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
cell.addSubview(cellTextLabel)
cellTextLabel.translatesAutoresizingMaskIntoConstraints = false
cellTextLabel.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10).isActive = true
cellTextLabel.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor, constant: -10).isActive = true
cellTextLabel.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 10).isActive = true
cellTextLabel.textColor = .white
cell.addSubview(cellDetailLabel)
cellDetailLabel.translatesAutoresizingMaskIntoConstraints = false
cellDetailLabel.leftAnchor.constraint(equalTo: imageView.rightAnchor, constant: 10).isActive = true
cellDetailLabel.rightAnchor.constraint(equalTo: cell.contentView.rightAnchor, constant: -10).isActive = true
cellDetailLabel.topAnchor.constraint(equalTo: cellTextLabel.bottomAnchor, constant: 10).isActive = true
cellDetailLabel.textColor = .white
cellDetailLabel.font = cellDetailLabel.font.withSize(12)
cellDetailLabel.numberOfLines = 3
cell.backgroundColor = .clear
cell.textLabel?.textColor = .white
cell.detailTextLabel?.textColor = .white
imageView.image = phImage
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var index = indexPath.row
if contentData.count > 0 {
cellTextLabel.text = contentData[index].title
cellDetailLabel.text = contentData[index].text
return cell
} else {
return cell
}
}
我在ViewDidLoad()
中configureCustomCell()
,感觉跟cellforRowAt
方法有关系,但我不确定。
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
configureCustomCell()
NewsAPI.shared.getData(arr: true) { (success) in
DispatchQueue.main.async {
self.contentData = NewsAPI.shared.contentData[0].posts
self.tableView.reloadData()
}
}
}
谢谢。
最佳答案
如下所示创建自定义 UITableViewCell
class CustomCell: UITableViewCell {
}
然后在 Controller viewDidLoad 中,您将按如下方式注册上面的单元格
tableView.registerClass(CustomCell.self, forCellReuseIdentifier: "CustomCell")
关于ios - 如何正确配置 UITableView 自定义单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52542017/