在使用UITableView的grouped样式时,系统会在每个section组以及头尾设置间距;如果想取消这些间距,可以使用一下方法:
1.首先消除顶部间距:
if #available(iOS 15.0, *) {
tableView.sectionHeaderTopPadding = 0
}
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .never
}
2.消除section之间的间距
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return nil
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.01
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
return nil
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.01
}
注意,这里的高度不能时0,否则系统会采用默认值;可以设置一个极小值,例如0.0001等。
3.消除底部间距
tableView.tableFooterView = UIView(frame: .init(origin: .zero, size: .init(width: 0.01, height: 0.01)))
同样,这里的高度也不能设置为0,否则系统会采用默认高度。