Why is there extra padding at the top of my UITabl

2018-12-31 17:09发布

Starting in iOS7, there is additional space at the top of my UITableView's which have a style UITableViewStyleGrouped.

Here is an example:

enter image description here

The tableview starts at the first arrow, there is 35 pixels of unexplained padding, then the green header is a UIView returned by viewForHeaderInSection (where the section is 0).

Can anyone explain where this 35 pixel amount is coming from and how I can get rid of it without switching to UITableViewStylePlain?

30条回答
何处买醉
2楼-- · 2018-12-31 17:44

Simply add the following to your viewDidLoad in your VC:

self.automaticallyAdjustsScrollViewInsets = NO;
查看更多
临风纵饮
3楼-- · 2018-12-31 17:45

While using grouped TableView use this to avoid border cutting in viewWillAppear

self.tableView.contentInset = UIEdgeInsetsMake(-35, 0, 0, 0);
查看更多
骚的不知所云
4楼-- · 2018-12-31 17:46

A lot of the previous answers above are too hacky. They would break at anytime in the future if Apple decides to fix this unexpected behavior.

Root of the issue:

  1. a UITableView doesn't like to have a header with a height of 0.0. If what's you're trying to do is to have a header with a height of 0, you can jump to the solution.

  2. even if later you assign a non 0.0 height to your header, a UITableView doesn't like to be assigned a header with a height of 0.0 at first.

Solution:

Then, the most simple and reliable fix is to ensure that your header height is not 0 when you assign it to your table view.

Something like this would work:

// 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;

Something like this would lead to the issue at some point (typically, after a scroll):

// Replace UIView with whatever class you're using as your header below:
UIView *tableViewHeaderView = [[UIView alloc] initWithFrame:CGRectZero];
self.tableView.tableHeaderView = tableViewHeaderView;
查看更多
几人难应
5楼-- · 2018-12-31 17:47

For IOS 7 if you are allocing a tableview in a view controller you may look into

self.edgesForExtendedLayout = UIRectEdgeNone;

your problem seemed similar to mine

Update:

Swift in iOS 9.x:

self.edgesForExtendedLayout = UIRectEdge.None

Swift 3 :

self.edgesForExtendedLayout = UIRectEdge.init(rawValue: 0)
查看更多
栀子花@的思念
6楼-- · 2018-12-31 17:47

I think making UIEdgeInsets -35 0 0 0 is tedious. In my case, I implemented tableView: heightForHeaderInSection: method and it has a potential to return 0.

When I changed 0 to 0.1f, the problem just went away.

查看更多
裙下三千臣
7楼-- · 2018-12-31 17:48

This is how it can be fixed easily in iOS 11 and Xcode 9.1 through Storyboard:

Select Table View > Size Inspector > Content Insets: Never

查看更多
登录 后发表回答