【发布时间】:2015-12-23 09:09:06
【问题描述】:
我希望在设置imageView.image 之后修改UICollectionView 的布局。
我想知道为我的可重用单元只执行一次代码的正确方法。
到目前为止,对我有用的方法是在 cellForRow() 方法中在其中绘制我的自定义视图,但这会使代码变得混乱。我想在单元格的类中执行代码。
Init(带框架)不起作用。我的collectionView 甚至都没有调用它。
此外,如果有人能快速解释一下UICollectionViewCell 最重要的方法是什么以及何时使用它们,我将不胜感激!
编辑:
这是我要从cellForRow() 中删除并移入单元格类的代码:
firstProductCell.imageView.image = UIImage(named: "photo1")
firstProductCell.textLabel.text = "Featured title"
let imgview: UIImageView = UIImageView(frame: CGRectMake(0, 0, 1100, 600))
imgview.image = firstProductCell.imageView.image
let whiteView: UIView = UIView(frame: CGRectMake(1200, 0, 600, 600))
whiteView.backgroundColor = UIColor.whiteColor()
let view: UIView = UIView(frame: cell.bounds)
view.addSubview(imgview)
view.addSubview(whiteView)
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0)
view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
firstProductCell.imageView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
【问题讨论】:
-
awakeFromNib?最好在问题中显示单次运行代码,因为它实际上可能不适合在单元格中... -
除了最后 4 行之外的所有内容似乎都可以使用界面生成器创建,无需代码。为什么要让单元格自己完成填充数据的工作,这就是 cellForRow 方法的工作。
-
我没有将
whiteView和imgView添加到单元格(将在Interface Builder 中创建)。我正在创建这些以创建两者的组合视图并将其添加为图像。将其添加为图像很重要,因为它受益于 tvOS 上的特殊动画。我不想在 Interface Builder 中创建它们。
标签: ios swift swift2 uicollectionviewcell