如何在原型单元格中使用UIImageView在UITableView中创建视差效果 [英] How do I create a parallax effect in UITableView with UIImageView in their prototype cells
问题描述
我正在使用Swift在iOS 8.4中构建一个应用程序。
I'm building an app in iOS 8.4 with Swift.
我有一个带有自定义的 UITableView
UITableViewCell
包含 UILabel
和 UIImageView
。这一切都很简单,一切都很好。
I have a UITableView
with a custom UITableViewCell
that includes a UILabel
and UIImageView
. This is all fairly straight forward and everything renders fine.
I'm trying to create a parallax effect similar to the one 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
}
该块存在于类似于类的类HomeController:UIViewController,UITableViewDelegate,UITableViewDataSource {...}
我也知道我可以通过 func scrollViewDidScroll
收听课堂上的滚动事件。
I am also aware that I can listen to scroll events in my class via func scrollViewDidScroll
.
除此之外,感谢帮助!
推荐答案
我想通了!我们的想法是在不实现任何额外库的情况下执行此操作,特别是考虑到实现的简单性。
I figured it out! The idea was to do this without implementing any extra libraries especially given the simplicity of the implementation.
首先...在自定义表视图中 Cell
类,您必须创建一个包装器视图。您可以在Prototype单元格中选择 UIImageView
,然后选择编辑器>嵌入>查看
。将两个拖动到Cell作为出口,然后为包含视图设置 clipToBounds = true
。 (还记得将约束设置为与图像相同。
First... in the custom table view Cell
class, you have to create an wrapper view. You can select your UIImageView
in the Prototype cell, then choose Editor > Embed in > View
. Drag the two into your Cell as outlets, then set clipToBounds = true
for the containing view. (also remember to set the constraints to the same as your image.
class MyCustomCell: UITableViewCell {
@IBOutlet weak var img: UIImageView!
@IBOutlet weak var imgWrapper: UIView!
override func awakeFromNib() {
self.imgWrapper.clipsToBounds = true
}
}
然后在你的 UITableViewController
子类(或委托)中,实现 scrollViewDidScroll
- 从这里你将不断更新 UIImageView
的 .frame
property。见下文:
Then in your UITableViewController
subclass (or delegate), implement the scrollViewDidScroll
— from here you'll continually update the UIImageView
's .frame
property. See below:
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)
}
}
这篇关于如何在原型单元格中使用UIImageView在UITableView中创建视差效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!