Adding a headerView to UIScrollView

A few weeks ago I came across this implementation that adds a footer view inside UIScrollView on github:
CLTableWithFooterViewController, where the author's demo looks like this:

but for my project I need to:

  • locate the view as a header instead
  • dragging down to show instead

and here is the code that follows the same approach as original poster's, but satisfying the two things my project looks for (sounds simple but took a lot of trails and errors to figure out...):

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    int totalHeightOfScrollView = scrollView.contentSize.height - self.headerButton.frame.size.height;
    float footerImageViewY = (totalHeightOfScrollView - scrollView.contentOffset.y);
    float headerImageViewY = footerImageViewY - totalHeightOfScrollView;

    float footerImageViewX = 0;
    float topEdge = - scrollView.contentOffset.y;

    if (topEdge >= 64) headerImageViewY = 64; // the height of navigationbar
    if (self.headerButton.frame.size.width < self.view.frame.size.width) {
        footerImageViewX = (self.view.frame.size.width/2)-(self.headerButton.frame.size.width/2);
    if(topEdge >=0 ){
        [self.view addSubview:self.headerButton];
        self.headerButton.frame = CGRectMake(footerImageViewX, headerImageViewY + 5, self.headerButton.frame.size.width, self.headerButton.frame.size.height);

Additionally, I added another line of code below to check the speed of scrolling. If the scrolling up speed is too fast, then it will put the view directly back to where it is.
The reason being, the implementation above works only when the scrolling is continuous. Therefore, if the scrolling is instantaneous/too fast, UIScrollView takes care of the scrolling momentum for you without you having to scroll, leaving the headerView to be stuck in the middle.

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    if(velocity.y > 0.5){
        self.headerButton.frame = CGRectMake(0, 0, self.headerButton.frame.size.width, self.headerButton.frame.size.height);

Note that both functions belong to UIScrollViewdelegate, and if there is a better implementation, please leave a message :)

comments powered by Disqus