Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move a view when scrolling in UITableView

I have a UIView with a UITableView below it:

enter image description here

What I would like to do is to have the view above the UITableView move up (out of the way) when the user starts scrolling in the table in order to have more space for the UITableView (and come down when you scroll down again).

I know that this is normally done with a table header view, but my problem is that my table view is inside a tab (actually it is a side-scrolling page view implemented using TTSliddingPageviewcontroller). So while I only have one top UIView there are three UITableViews.

Is it possible to accomplish this manually? My first thought is to put everything in a UIScrollView, but according to Apple's documentation one should never place a UITableView inside a UIScrollView as this leads to unpredictable behavior.

like image 598
pajevic Avatar asked Aug 19 '14 00:08

pajevic


People also ask

Is UITableView scrollable?

UITableView scrolls back because it's content size is equal to it's frame (or near to it). If you want to scroll it without returning you need add more cells: table view content size will be large then it's frame.


2 Answers

Solution for Swift (Works perfectly with bounce enabled for scroll view):

 var oldContentOffset = CGPointZero  let topConstraintRange = (CGFloat(120)..<CGFloat(300))   func scrollViewDidScroll(scrollView: UIScrollView) {      let delta =  scrollView.contentOffset.y - oldContentOffset.y      //we compress the top view     if delta > 0 && topConstraint.constant > topConstraintRange.start && scrollView.contentOffset.y > 0 {         topConstraint.constant -= delta         scrollView.contentOffset.y -= delta     }      //we expand the top view     if delta < 0 && topConstraint.constant < topConstraintRange.end && scrollView.contentOffset.y < 0{         topConstraint.constant -= delta         scrollView.contentOffset.y -= delta     }      oldContentOffset = scrollView.contentOffset  } 
like image 148
George Muntean Avatar answered Sep 21 '22 19:09

George Muntean


Since UITableView is a subclass of UIScrollView, your table view's delegate can receive UIScrollViewDelegate methods.

In your table view's delegate:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    static CGFloat previousOffset;
    CGRect rect = self.view.frame;
    rect.origin.y += previousOffset - scrollView.contentOffset.y;
    previousOffset = scrollView.contentOffset.y;
    self.view.frame = rect;
}
like image 28
NobodyNada Avatar answered Sep 21 '22 19:09

NobodyNada