UITableVIew header without bouncing when pull down

前端 未结 3 1419
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 20:39

I have a UITableView which I am able to add a header view to fairly easily. Many apps (like Facebook, for viewing events) have a headerView that when you pull d

相关标签:
3条回答
  • 2020-12-13 21:23

    You can achieve this effect quite easily by adding a subview to the header view and adjusting its frame or transform when the table view is scrolled beyond the top, i.e. the y component of its contentOffset becomes negative.

    Example (in a UITableViewController subclass):

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        CGFloat headerHeight = 64.0f;
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, headerHeight)];
        UIView *headerContentView = [[UIView alloc] initWithFrame:headerView.bounds];
        headerContentView.backgroundColor = [UIColor greenColor];
        headerContentView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [headerView addSubview:headerContentView];
        self.tableView.tableHeaderView = headerView;
    }
    
    //Note: UITableView is a subclass of UIScrollView, so we
    //      can use UIScrollViewDelegate methods.
    - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        CGFloat offsetY = scrollView.contentOffset.y;
        UIView *headerContentView = self.tableView.tableHeaderView.subviews[0];
        headerContentView.transform = CGAffineTransformMakeTranslation(0, MIN(offsetY, 0));
    }
    

    (to keep it simple, I've just used the first subview of the actual header view in scrollViewDidScroll:, you may want to use a property for that instead.)

    0 讨论(0)
  • 2020-12-13 21:28

    There is 2 ways you can set the table header:

    • Using the .tableHeaderView property directly (this header scrolls with the table)

    • Overriding the - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section function (this header stays static with the section)

    By the sounds of it you should use the 2nd method instead of using the .tableHeaderView property

    0 讨论(0)
  • 2020-12-13 21:36

    Your UITableView is most likely working properly. Section headers are sticky by default in Plain style tables. Meaning as you scroll down the header stays at the top of the UITableView's frame until the next section header pushes it out of the way. The opposite occurs when you scroll up. Conversely you get the sticky behavior on section footers at the bottom of the UITableView's frame.

    EDIT Misunderstood the original question:

    I would suggest using a section header rather than the table view header to get the sticky behavior you're looking for.

    Include a section in your data with no rows and put your table header's view in that section header view.

    0 讨论(0)
提交回复
热议问题