Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a UIView above viewable area of a UITableView?

I understand that there is a tableHeaderView property, but when ever I add my view to that, it is not hidden above the scroll area.

What I would like to have is, my custom view shown when you pull down the tableview and hold and you see my UIView brought into view. This is done on many apps to put a logo or such slightly hidden until a user pulls down on the tableview (Twitter/Facebook when you pulldown).

I am currently using the following and it is not putting it out of the view:

    UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 20)];
    l.text = @"Hidden Text";
    l.textColor = [UIColor redColor];
    self.tableView.tableHeaderView = l;
    [l release];
like image 314
Nic Hubbard Avatar asked Feb 28 '11 23:02

Nic Hubbard


Video Answer


2 Answers

Since UITableView is actually a UIScrollView with some extra functionality, you can use contentInset to obtain the effect you want. The trick is to use a negative value for the top inset. This will normally hide your header view, but it will still be viewable when the table bounces.

So, after you add the label to the header view, just set the contentInset like this:


    UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 20)];
    l.text = @"Hidden Text";
    l.textColor = [UIColor redColor];
    self.tableView.tableHeaderView = l;

    //add this
    [self.tableView setContentInset:UIEdgeInsetsMake(-l.bounds.size.height, 0.0f, 0.0f, 0.0f)];

    [l release];
like image 101
Andrei Stanescu Avatar answered Oct 06 '22 19:10

Andrei Stanescu


The best solution here is to add your view to the header, as you had mentioned you tried, and then in your controller's viewDidLoad actually scroll the tableview downward programmatically until the header view you wanted hidden is hidden. This can be done a number of different ways. The easiest is probably:

[self.tableView setContentOffset: CGPointMake(0, myHeaderHeight)];
like image 25
Micah Hainline Avatar answered Oct 06 '22 18:10

Micah Hainline