ios - tableview 图像上的视差,使用自动布局

标签 ios uitableview autolayout uistoryboard parallax

我有几个宽度大于高度的表格 View 单元格。因此,我正在实现视差滚动,以便您在向上/向下滚动时可以看到更多图像

Example of desired effect

关注一些 code examples几乎让我到达那里,但是当我使用 AutoLayout 时,我发现当您第一次开始滚动时会出现“跳跃”,这是由于实际图像位置和预期位置的差异。我已经尝试在 viewDidAppear 和 didLayoutSubviews 上调用布局函数,以尝试在第一次设置后将其调整到位,但没有成功。

This answer suggests a solution using AutoLayout 这看起来很简洁,所以我首先调整了代码,但它仍然跳转。如果我使用该答案中建议的代码,它会无处不在

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;

现在发生了什么,滚动效果很好,但是一旦您开始第一次滚动,元素就会跳下大约 30 像素。所以我需要它在没有这个初始跳跃的情况下工作吗?

初始屏幕加载:

enter image description here

滚动 1 像素后(注意第一张和最后一张图像的跳转):

enter image description here

最佳答案

我已经更新了链接 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;
    }
}

现在,我没有将约束常量更改为 ScrollView 内容偏移量,而是引入了 cellRect 以确保单元格位于 tableview 顶部时的约束常量为零。

您可以找到样本 here .

关于ios - tableview 图像上的视差,使用自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33854323/

相关文章:

ios - 应用程序崩溃 : Index out of bound at random places

ios - 拖动通过 SKPhysicsJoints 连接的 Sprite 的最佳方式?

ios - 如何在 Swift 的 maintableviewcell 中访问内部 tableviewcell 的高度

cocoa - 如何以视觉格式设置自动布局默认间距指标的优先级?

ios - UILabel 大小更改不会通过自动布局进行动画处理

ios - 有没有办法在 UIView 大小更改时自动更新约束?

iphone - 使用 NSFileManager 复制文件期间更新进度条

ios - 使用 AES 进行部分加密 - IOS 应用程序

ios - 在 TableView 中保存右行

ios - 为什么 UITableView 单元格在滚动时重叠?