从iOS7开始,在我的UITableView顶部有额外的空间它有一个UITableViewStyleGrouped样式。
这里有一个例子:
tableview从第一个箭头开始,有35个像素的无法解释的填充,然后绿色的头是一个由viewForHeaderInSection返回的UIView(其中section为0)。
有人能解释一下这个35像素的数量是从哪里来的吗?我如何才能在不切换到UITableViewStylePlain的情况下摆脱它?
更新(回答):
在iOS 11及更高版本中:
tableView.contentInsetAdjustmentBehavior = .never
根据苹果的文档:
当将视图分配给此属性时,将该视图的高度设置为
一个非零值。表视图只尊重您的高度
视图的框架矩形;它调整你的头视图的宽度
自动匹配表视图的宽度。
斯威夫特5
如果你有一个分组UITableView,你想要一个tableHeaderView:
在将视图分配给tableView之前。tableHeaderView,设置该视图的高度为一个非零值,例如:
// Set the initial height of your custom view to the smallest value
myTableHeaderView.frame.size.height = .leastNonzeroMagnitude
// Assign your custom view to the header view
tableView.tableHeaderView = myTableHeaderView
// Set width constraint, height should grow based on your view.
tableView.tableHeaderView!.widthAnchor.constraint(equalTo: tableView.widthAnchor).isActive = true
不需要使用contentInsets或处理委托方法。
我假设这只是新UITableViewStyleGrouped样式的一部分。它存在于所有分组表视图中,似乎没有任何直接的方法来控制该空间。
如果这个空间是由一个UIView表示的,那么可以搜索UITableView的所有子视图来找到那个特定的视图并直接编辑它。然而,也有可能该空间只是标题和单元格开始之前的硬编码偏移量,没有任何方法来编辑它。
要搜索所有子视图(我将在表没有单元格时运行这段代码,以使它更容易阅读输出):
- (void)listSubviewsOfView:(UIView *)view {
// Get the subviews of the view
NSArray *subviews = [view subviews];
// Return if there are no subviews
if ([subviews count] == 0) return;
for (UIView *subview in subviews) {
NSLog(@"%@", subview);
// List the subviews of subview
[self listSubviewsOfView:subview];
}
}
这段代码对我来说很有用,对我来说最好的答案是用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
}
}