3
votes

I have a controller, which has a UIView at the top with some buttons and labels. Underneath that I have a UIScrollView that contains content as well. I want the UIView on top to essentially work and appear as a header to this scroll view, similar to a UITableViewHeader. I'm using the scrollViewDidScroll delegate method with the contentOffset to try and get it to work, but I can't seem to get the right math.

The idea is that as the scroll view scrolls up the "header" will scroll up with it relative to the content. It can even scroll off screen. Then as you scroll down it will stick to the top of the scroll view. Like I said, very similar functionality to a UITableViewHeader.

Any help with figuring out the math for this would be greatly appreciated!

Here is what I have so far:

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGRect updatedSegmentFrame = self.segmentedControlContainerView.bounds;
    CGRect updatedTableViewFrame = self.viewControllerThree.tableView.frame;

    CGFloat topEdge = -scrollView.contentOffset.y;

    if (topEdge >= 0) {
        updatedSegmentFrame.origin.y = 0;
    }
    else {
        updatedSegmentFrame.origin.y = -scrollView.contentOffset.y;
    }

    self.viewControllerThree.tableView.frame = updatedTableViewFrame;
    self.segmentedControlContainerView.frame = updatedSegmentFrame;
}

This code moves the external "header view" along with the UIScrollView with everything working as expected. The only thing missing is that as you scroll up the UIScrollView will need to get larger to offset the headerView going off the screen.

1
Can you post what you have so far? - Acey
@Acey Just added it. - BlueBear
Do you want it to behave similar to the Game screen in the Game Center App, where the segment controller sticks to the top, and the top portion scrolls off-screen? If so, I would offer a slightly different approach. - Sheamus
Use constraint that is far easier. - GaƩtanZ

1 Answers

1
votes

Here is a solution I provided for a header that behaves similarly to what you're describing: FixedHeaderTableView.

In your case, you would pass in 0 for the visibleHeaderHeight parameter.