我有一个 UITableView 作为另一个 UITableView (嵌套 UITableView)的单元格。 有一个我无法解释的顶部填充,仅当我使 CustomTableCell 具有 UITableView 时才会出现顶部填充。
class CustomTableCell: UITableViewCell, UITableViewDelegate, UITableViewDataSource {
private let cellId = "cellId"
lazy var tableView: UITableView = {
let tv = UITableView(frame: .zero, style: .grouped)
tv.translatesAutoresizingMaskIntoConstraints = false
tv.backgroundColor = .green
tv.delegate = self
tv.dataSource = self
tv.alwaysBounceVertical = false
tv.isScrollEnabled = false
tv.separatorColor = .red;
tv.separatorStyle = .none;
tv.register(InnerTableCell.self, forCellReuseIdentifier: self.cellId)
return tv
}()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! InnerTableCell
return cell
}
func setupAutoLayout() {
tableView.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true
tableView.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = .white
contentView.addSubview(tableView)
setupAutoLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
这是整个代码的链接:https://ideone.com/QAxkPR
将样式更改为
.plain
而不是 .grouped
let tv = UITableView(frame: .zero, style: .plain)
如果您使用
.plain
表格样式,则会自动添加此填充。
有关 TableView 样式的更多信息: https://developer.apple.com/documentation/uikit/uitableview/style
如果这适用于您的用例,您可以通过切换到
.grouped
来修复它 - 但这会阻止节标题锚定到顶部并保持在视图中。
如果您想继续使用
.plain
样式表,另一种修复方法是设置
tableView.sectionHeaderTopPadding = 0