Parallax on tableview image, using Auto Layout

拟墨画扇 提交于 2019-12-25 09:59:14

问题


I have several tableview cells which are wider than they are tall. As such, I'm implementing a parallax scroll so you can see more of the image as you scroll up/down

Example of desired effect

Following some code examples nearly gets me there, but as I'm using AutoLayout, I find there is a 'jump' when you first start scrolling, due to the difference in actual image positions and the expected position. I've tried calling the layout function on both viewDidAppear and didLayoutSubviews to try and kick it into shape after the first setup, but no luck.

This answer suggests a solution using AutoLayout which seems very succint, so I've adjusted the code in the first, however it still jumps. If I use the code suggested in that answer, it goes all over the place

CGRect rectInSuperview = [tableView convertRect:self.frame toView:view];

float distanceFromCentre = CGRectGetHeight(view.frame)/2 - CGRectGetMinY(rectInSuperview);
float difference = CGRectGetHeight(self.eventImage.frame) - CGRectGetHeight(self.frame);
float move = (distanceFromCentre / CGRectGetHeight(view.frame)) *difference;

CGRect imageRect = self.eventImage.frame;
imageRect.origin.y = -(difference/2)+move;
self.verticalCenter.constant = move;

what happens now, is the scrolling works great, but elements jump down by about 30px ish as soon as you start to first scroll. So I need it to work without this initial jump?

Initial screen load:

After scrolling by 1px (notice jump of first and last images):


回答1:


I have updated the linked answer,

@implementation TableViewController

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {

    NSArray * cells =  [self.tableView visibleCells];
    for (TableViewCell* cell in cells) {
        NSIndexPath * indexPathOfCell = [self.tableView indexPathForCell:cell];
        CGRect cellRect = [self.tableView rectForRowAtIndexPath:indexPathOfCell];
        cell.verticalCenter.constant = (scrollView.contentOffset.y -cellRect.origin.y)/kParallaxRatio;
    }
}

Now, instead of changing constraint constant to scrollview content offset, I have introduced the cellRect to makes sure that the cell's constraint constant is zero when it is at the top of the tableview.

You can find the sample here.



来源:https://stackoverflow.com/questions/33854323/parallax-on-tableview-image-using-auto-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!