UITableView + 在顶部添加内容偏移量

我需要在我的 UITableView 顶部添加一些不影响内容区域大小的空白。将内容向下移动或添加一个空白单元格不是我想要做的。相反,我只是想要一个抵消。

怎么做到的?

87535 次浏览

You can add an "empty" header view to the table... this would give the initial appearance of the table to have an offset, but once you started scrolling the offset would be gone. NOt sure that's what you want.

If you need a permanent offset and are not already using section headers, then you could create the offset similarly to above by making custom views for the section headers, especially if you just have one section, this could give you the look of a permanent offset.

I can post sample code if it sounds like either of those are what you are looking for.

Sounds like you want to wrap a 'View' around your UITableView. If you have a UITableViewController in IB the UITableView will automatically be set to the view of UITableViewController. You change view property to a normal UIView and add your UITableView in there and give it a offset.

---Edit--- I just read my post and thought it made little sense :) When you create a UITableViewController you get this (in pseudo code):

UITableViewController.view = UITableView

This means that the actual table will take up the whole space and you cannot even add other views. So you need to change the

UITableViewController.view = UIView

and add your table to that UIView

I'm not sure if I'm following you but I think I'm having the same predicament. In my case I must give some space to the ADBannerView at the top of the screen so what I did was in the viewDidLoad method I added:

[self.tableView setContentInset:UIEdgeInsetsMake(50,0,0,0)];

the values it takes are UIEdgeInsetsMake(top,left,bottom,right).

Alternatively the same with Swift:

self.tableView.contentInset = UIEdgeInsetsMake(50, 0, 0, 0)

Swift 4.2:

self.tableView.contentInset = UIEdgeInsets(top: 50, left: 0, bottom: 0, right: 0)

I combined Jigzat's answer with:

[self.tableView scrollRectToVisible:CGRectMake(0, 0, 320, 1) animated:NO];

in

- (void)viewDidLoad

so the first cell isn't at the top.

I combined this answer with this one: https://stackoverflow.com/a/9450345/1993937

To make the tableView appear at the top of the content inset, so the space at the top isn't cut off by having the tableView scrolled down slightly when the view initially appears. (18 is my top gap)

[self.tableView setContentInset:UIEdgeInsetsMake(18,0,0,0)];
[self.tableView setContentOffset:
CGPointMake(0, -self.songListTable.contentInset.top) animated:YES];

Swift 5.1

add the following in viewDidLoad

tableView.contentInset.top = 100

Really that's all there is to it.

override func viewDidLoad() {
super.viewDidLoad()
tableView.contentInset.top = 100
}