从iOS7开始,在我的UITableView顶部有额外的空间它有一个UITableViewStyleGrouped样式。
这里有一个例子:
tableview从第一个箭头开始,有35个像素的无法解释的填充,然后绿色的头是一个由viewForHeaderInSection返回的UIView(其中section为0)。
有人能解释一下这个35像素的数量是从哪里来的吗?我如何才能在不切换到UITableViewStylePlain的情况下摆脱它?
更新(回答):
在iOS 11及更高版本中:
tableView.contentInsetAdjustmentBehavior = .never
我遇到了同样的问题,但是tableView在tableView单元格中。
上面的无数答案都不起作用。
一个非常奇怪而简单的东西起了作用:
-在为tableView分配委托之前,放置估计的高度!!
override func awakeFromNib() {
super.awakeFromNib()
tableView.estimatedRowHeight = 58
tableView.estimatedSectionHeaderHeight = 45
tableView.estimatedSectionFooterHeight = 10
tableView.dataSource = self
tableView.delegate = self
}
将估计放在委托分配之后,导致我的内部tableView在标题上方有一个奇怪的空白。
我希望它能帮助到这里的人。
当你使用UITableView.Style.grouped或UITableView.Style.InsetGrouped时,如果没有“tableview header”,tableview将自动添加一个顶部inset填充到“section header”,修复很简单:
self.tableview.tableFooterView = UIView(frame: CGRect.init(origin: .zero, size: CGSize.init(width: tableview.frame.size.width, height: 1)))
self.tableview.tableHeaderView = UIView(frame: CGRect.init(origin: .zero, size: CGSize.init(width: tableview.frame.size.width, height: 1)))
如果你使用uitableview。style。plain
self.tableview.contentInsetAdjustmentBehavior = .never
一般来说就足够了
上面的很多答案都太俗气了。如果苹果决定修复这种意外的行为,它们在未来的任何时候都会崩溃。
问题的根源:
UITableView不喜欢头的高度为0.0。如果你要做的是有一个高度为0的标题,你可以跳到解决方案。
即使以后你给你的头分配了一个非0.0的高度,UITableView也不喜欢一开始就被分配一个高度为0.0的头。
解决方案:
然后,最简单可靠的修复方法是确保头高度在分配给表视图时不为0。
这样做是可行的:
// Replace UIView with whatever class you're using as your header below:
UIView *tableViewHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.tableView.bounds.size.width, CGFLOAT_MIN)];
self.tableView.tableHeaderView = tableViewHeaderView;
这样的事情会在某些时候(通常是在滚动之后)导致问题:
// Replace UIView with whatever class you're using as your header below:
UIView *tableViewHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
self.tableView.tableHeaderView = tableViewHeaderView;
这段代码对我来说很有用,对我来说最好的答案是用objective-C写的,所以我把它转换成Swift。
针对Swift 4.0+
self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: .leastNonzeroMagnitude))
只需将其写入viewDidLoad(),它就会像一个咒语一样工作。
对于iOS 15+,上面的一个将不起作用,所以使用这个:-
if #available(iOS 15.0, *) {
tableView.sectionHeaderTopPadding = 0
}
对于iOS 15+,如果你想为你的整个项目应用更改,那么使用这个:-
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if #available(iOS 15.0, *) {
UITableView.appearance().sectionHeaderTopPadding = 0.0
}
}