UITableView Paallax Background a la Path

2923 ワード

Original Link:
http://rowboatrevolution.com/2012/02/uitableview-parallax-background-a-la-path/
Path does a clever litle parallax trick when you overscroll the main timeline view.This effect gives a nice sense of depth between the tableview and background image.
Reproducing it is quite easury,and only requires a few entry points.
The gist:give the UItable View a tranparent header,through which we see the positiond backgroundイメージ.When the user scrolls,if the scroll offset is negative,position the undering image imation.
1.Add a UImageView behind the UItable View and offset it a bit vertically from its nature state.This gives some room for it to move vertically and still be onscreen.

- (void)viewDidLoad {
    [super viewDidLoad];

    // Create an empty table header view with small bottom border view
    UIView *tableHeaderView = [[UIView alloc] initWithFrame: CGRectMake(0.0, 0.0, self.view.frame.size.width, 180.0)];
    UIView *blackBorderView = [[UIView alloc] initWithFrame: CGRectMake(0.0, 179.0, self.view.frame.size.width, 1.0)];
    blackBorderView.backgroundColor = [UIColor colorWithRed: 0.0 green: 0.0 blue: 0.0 alpha: 0.8];
    [tableHeaderView addSubview: blackBorderView];
    [blackBorderView release];
    
    _tableView.tableHeaderView = tableHeaderView;
    [tableHeaderView release];
    
    // Create the underlying imageview and offset it
    _headerImageYOffset = -150.0;
    _headerImage = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"header-image.png"]];
    CGRect headerImageFrame = _headerImage.frame;
    headerImageFrame.origin.y = _headerImageYOffset;
    _headerImage.frame = headerImageFrame;
    [self.view insertSubview: _headerImage belowSubview: _tableView];
}
2.Hook up your controller as a UICrollView Delegate and implement the scrollView DidScrroll calback.
3.For each call、move the undering image a multiple of the scroll offset.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat scrollOffset = scrollView.contentOffset.y;
    CGRect headerImageFrame = _headerImage.frame;
    
    if (scrollOffset < 0) {
         // Adjust image proportionally
        headerImageFrame.origin.y = _headerImageYOffset - ((scrollOffset / 3));
    } else {
         // We're scrolling up, return to normal behavior
        headerImageFrame.origin.y = _headerImageYOffset - scrollOffset;
    }
    _headerImage.frame = headerImageFrame;
}
You could take this even further by having multively offset、creating a nice multi-layer parallax.