ios - 如何在原型(prototype)单元格中使用 UIImageView 在 UITableView 中创建视差效果

标签 ios swift uitableview parallax

我正在使用 Swift 在 iOS 8.4 中构建应用。

我有一个带有自定义 UITableViewCellUITableView,其中包括一个 UILabelUIImageView。这一切都相当简单,一切都很好。

我正在尝试创建类似于 demonstrated in this demo 的视差效果.

目前我的 tableView.cellForRowAtIndexPath 中有这段代码

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = self.tableView.dequeueReusableCellWithIdentifier("myitem", forIndexPath: indexPath) as! MixTableViewCell
    cell.img.backgroundColor = UIColor.blackColor()
    cell.title.text = self.items[indexPath.row]["title"]

    cell.img.image = UIImage(named: "Example.png")

    // ideally it would be cool to have an extension allowing the following
    // cell.img.addParallax(50) // or some other configurable offset

    return cell
}

该 block 存在于一个看起来像 class HomeController: UIViewController, UITableViewDelegate, UITableViewDataSource { ... }

的类中

我也知道我可以通过 func scrollViewDidScroll 在我的类中监听滚动事件。

除此之外,我们将不胜感激!

最佳答案

我想通了!我们的想法是在不实现任何额外库的情况下做到这一点,特别是考虑到实现的简单性。

首先...在自定义 TableView Cell 类中,您必须创建一个包装 View 。您可以在 Prototype 单元格中选择 UIImageView,然后选择 Editor > Embed in > View。将两者作为导出拖到您的 Cell 中,然后为包含 View 设置 clipToBounds = true。 (还记得将约束设置为与您的图像相同。

class MyCustomCell: UITableViewCell {
    @IBOutlet weak var img: UIImageView!
    @IBOutlet weak var imgWrapper: UIView!
    override func awakeFromNib() {
        self.imgWrapper.clipsToBounds = true
    }
}

然后在您的 UITableViewController 子类(或委托(delegate))中,实现 scrollViewDidScroll — 从这里您将不断更新 UIImageView.frame 属性。见下文:

override func scrollViewDidScroll(scrollView: UIScrollView) {
    let offsetY = self.tableView.contentOffset.y
    for cell in self.tableView.visibleCells as! [MyCustomCell] {
        let x = cell.img.frame.origin.x
        let w = cell.img.bounds.width
        let h = cell.img.bounds.height
        let y = ((offsetY - cell.frame.origin.y) / h) * 25
        cell.img.frame = CGRectMake(x, y, w, h)
    }
}

See this in action .

关于ios - 如何在原型(prototype)单元格中使用 UIImageView 在 UITableView 中创建视差效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31373775/

相关文章:

ios - ALAssetsLibrary 从自定义相册中获取图像 ios

ios - insertRowsAtIndexPaths 中的 NSInternalInconsistencyException

iphone - 每 14 天(两周)重复一次本地通知?

swift - 结构中的委派初始值设定项未标记为 'convenience'

ios - Swift - 在 KeyWindow 的 subview 中无法识别点击手势

ios - 访问在 Storyboard 中创建的自定义 uitableviewcell 中的文本标签

安卓/iOS : Titanium Appcelerator horizontal scrolling

ios - 如何从内存中删除子类化的 SKNode?

ios - 从 iOS 中 UITableView 中的单元格中分离

swift - 如何将 UITableView 从 nib 文件加载到父 View Controller 中的容器 View 中?