要解决表格视图标题栏重叠单元格的问题,你可以使用以下代码示例:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// 创建表格视图
tableView = UITableView(frame: view.bounds, style: .plain)
tableView.delegate = self
tableView.dataSource = self
// 注册单元格
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
// 调整标题栏边距
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .never
} else {
automaticallyAdjustsScrollViewInsets = false
}
view.addSubview(tableView)
}
// 表格视图数据源方法
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = "Row \(indexPath.row)"
return cell
}
// 表格视图代理方法
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 50))
headerView.backgroundColor = .gray
let titleLabel = UILabel(frame: headerView.bounds)
titleLabel.text = "Table View Header"
titleLabel.textAlignment = .center
titleLabel.textColor = .white
headerView.addSubview(titleLabel)
return headerView
}
}
在这个示例中,我们创建了一个简单的表格视图,包含一个带有标题栏的自定义表头视图。要解决标题栏重叠单元格的问题,我们设置了表格视图的contentInsetAdjustmentBehavior
属性,该属性在iOS 11及以上版本中可用。如果设备运行的是较早的iOS版本,我们则将automaticallyAdjustsScrollViewInsets
属性设置为false
。
这样,标题栏就不会重叠在单元格上了。
上一篇:表格视图的标题