我正在使用 Swift 在 iOS 8.4 中构建应用。
我有一个带有自定义 UITableViewCell
的 UITableView
,其中包括一个 UILabel
和 UIImageView
。这一切都相当简单,一切都很好。
我正在尝试创建类似于 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)
}
}
关于ios - 如何在原型(prototype)单元格中使用 UIImageView 在 UITableView 中创建视差效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31373775/