Alan
Alan

Reputation: 9471

How to collapse UITableView header as you scroll

The functionality I am trying to achieve is shown in Twitter here.

I have been looking at several resources online including this article by Michigan Labs which is very useful in getting the collapsing animation by using constraints on a header view that is above the UITableView

The problem I see with this approach is that since it is not technically part of the UITableView, the header will not be responding to Up/Down scroll gestures. However, when I download the Twitter app, the header does respond to touch. How do I make the header sensitive to touch gestures as well?

Summary: I want to duplicate that middle section where it shows the profile picture, followers, buttons, and segmented control that collapses until only the segmented control is showing.

Upvotes: 2

Views: 1881

Answers (1)

LGP
LGP

Reputation: 4333

The scroll view exposes it's gesture handler so you can just add it to your view and it should work.

view.addGestureRecognizer(scrollView.panGestureRecognizer)

Also, since the header seems to be inside the table view, you can clear the userInteractionEnabled for the header view, and it will send the gestures to the underlying view instead.

Edit: Since the gesture only can belong to a single view at a time I suggest this method instead. Override the hittest lower level method on UIView to steer events to the correct view. Implement this on your header view, and always return the table view. You can add the table view as a property on the header view, and set it in viewDidLoad.

override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
    if self.pointInside(point, withEvent: event)
        return self.tableView
    return nil;
 }

(Objective-C version below)

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if ([self pointInside:point withEvent:event])
        return _nextView;
    return nil;
}

Upvotes: 1

Related Questions