Skip to content

Instantly share code, notes, and snippets.

@jashenson
Created November 27, 2013 23:39

Revisions

  1. @jayred jayred created this gist Nov 27, 2013.
    41 changes: 41 additions & 0 deletions JSTableWithFixedHeaderViewController.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    // Key sections of code for this implementation are placed below

    @interface JSTableWithFixedHeaderViewController ()

    @property (strong, nonatomic) UIView *fixedHeaderView;

    @end

    @implementation JSTableWithFixedHeaderViewController

    // The following code will insert our custom fixed header view in the appropriate hierarchy
    - (void) viewWillAppear:(BOOL)animated
    {
    CGSize intrinsicSize = self.fixedHeaderView.intrinsicContentSize;
    CGHeight height = (intrinsicSize.height > 0) ? intrinsicSize.height : 30; // replace with some fixed value as needed
    CGFloat width = CGRectGetWidth(self.view.bounds);
    CGRect frame = CGRectMake(0, 0, width, height);

    self.fixedHeaderView.frame = frame;
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(height, 0, 0, 0);

    UIView *wrapperView = self.tableView.subviews[0]; // this is a bit of a hack solution, but should always pull out the UITableViewWrapperView
    [self.tableView insertSubview:self.fixedHeaderView aboveSubview:wrapperView];
    }

    - (void) scrollViewDidScroll:(UIScrollView *)scrollView
    {
    // Adjust the header's frame to keep it pinned to the top of the scroll view
    CGRect headerFrame = self.fixedHeaderView.frame;
    CGFloat yOffset = scrollView.contentOffset.y;
    headerFrame.origin.y = MAX(0, yOffset);
    self.fixedHeaderView.frame = headerFrame;

    // If the user is pulling down on the top of the scroll view, adjust the scroll indicator appropriately
    CGFloat height = CGRectGetHeight(headerFrame);
    if (yOffset< 0) {
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(ABS(yOffset) + height, 0, 0, 0);
    }
    }

    @end