在表视图中,行为空可能由多种原因造成。以下是一些常见的解决方法,包含代码示例:
// 数据源示例
let data = ["行1", "行2", "行3"]
// 在表视图的数据源方法中返回正确的行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
// 注册单元格
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CellIdentifier")
// 在数据源方法中使用相同的重用标识符
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath)
// 配置单元格的内容
cell.textLabel?.text = data[indexPath.row]
return cell
}
// 在表视图的代理方法中返回正确的行高
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
// 在视图控制器的视图加载方法中设置约束
override func viewDidLoad() {
super.viewDidLoad()
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
通过检查数据源、重用标识符、单元格高度和表视图的约束,您应该能够解决表视图中行为空的问题。