iOS 15 中 UITableViewSections 之间的额外空间

Extra Space Between UITableViewSections in iOS 15

提问人:lazarevzubov 提问时间:10/6/2021 最后编辑:lazarevzubov 更新时间:10/10/2021 访问量:2693

问:

UITableView有多个部分没有部分页脚,部分之间有额外的空间。Xcode 的视图调试器显示它不是一个视图,而只是一个空白区域。

就我而言,这种行为是不需要的。

尝试添加 1.0/0.0 高度的页脚无济于事。更改表视图的 .style

下面是一个示例代码:

import UIKit
 
final class ViewController: UITableViewController {
 
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.separatorColor = .yellow
    }
 
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
 
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView()
        header.backgroundColor = .green
 
        return header
    }
 
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20.0
    }
 
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
 
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.backgroundColor = .blue
 
        return cell
    }
 
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 30.0
    }
 
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = UIView()
        footer.backgroundColor = .red
 
        return footer
    }
 
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 20.0
    }
 
}

以下是 iOS 14 和 iOS 15 中的输出:

iOS 14 iOS 15

iOS 版UIKitiTioS15

评论

0赞 Eduardo Santi 10/6/2021
重复的问题...请参阅此处以解决您的问题:stackoverflow.com/a/69350529/6883935
0赞 lazarevzubov 10/7/2021
@EduardoSanti 不,不是。在您指出的问题中,有人询问其表格视图周围的边距。我问各部分之间的空白。被接受的答案包含我问题的解决方案,但该问题的作者说这不是他们问题的解决方案。
0赞 Eduardo Santi 10/7/2021
对不起,我看错了。是否使用 heightForHeaderInSection 委托方法?
0赞 lazarevzubov 10/9/2021
我尝试了使用和不使用,并尝试使用 0.0 和 1.0 高度——它不会影响空间。正如我所提到的,Xcode 的视图调试器显示各部分之间没有标题(或任何其他视图),只是一个空白区域。而这个空间只出现在 iOS 15 中。heightForHeaderInSection
0赞 Eduardo Santi 10/9/2021
你能分享一下图片吗?

答:

17赞 lazarevzubov 10/6/2021 #1

在 iOS 15 中添加了该属性。它会影响那个确切的空间。该属性的默认值为 。将其设置为 0.0 可解决此问题。sectionHeaderTopPaddingautomaticDimension

由于该属性仅在 iOS 15 中可用,因此您可能希望使用可用性块将其包装起来:

if #available(iOS 15.0, *) {
  tableView.sectionHeaderTopPadding = 0.0
}

以下是该问题的原始代码片段,包括必要的更改:

import UIKit
 
final class ViewController: UITableViewController {
 
    override func viewDidLoad() {
        super.viewDidLoad()
 
        tableView.separatorColor = .yellow
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0.0
        }
    }
 
    // The rest is without changes.
 
}

以下是更改后 iOS 15 中的输出:

iOS 15 after update