ios - 我应该在 UICollectionViewCell 的哪个方法中编写只运行一次的代码?

标签 ios swift swift2 uicollectionviewcell

我希望在 UICollectionView 设置其 imageView.image 之后修改它的布局。

我想知道为我的可重用单元只执行一次我的代码的正确方法。

到目前为止,对我有用的方法是在 cellForRow() 方法中在其中绘制我的自定义 View ,但这会使代码变得困惑。我想在单元格的类中执行代码。

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()

最佳答案

不幸的是,我没有看到您是如何创建单元格的,但是: 如果您将自定义单元格类注册到您的 collectionView:

    collection.registerClass(CustomCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "CellIdentifier")

然后在 cellForItemAtIndexpath 中使用:

let cell : CustomCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("CellIdentifier", forIndexPath: indexPath) as! CustomCollectionViewCell

然后将调用 CustomCollectionViewCell 的 init with frame 方法:

override init(frame: CGRect)
    {
        super.init(frame: frame)
    }

关于ios - 我应该在 UICollectionViewCell 的哪个方法中编写只运行一次的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34432073/

相关文章:

ios - 等待进入 Controller ,直到 wifi 启用 IOS

ios - 可选([值])!产生 nil (错误),尽管它有一个值

ios - 检测 Sprite 纹理内的触摸而不是整个框架 iOS Swift SpriteKit?

swift - 无法快速将变量传递到 spritekit 中的场景

ios - Swift 2 迁移后,obj c 程序看不到 Swift 程序

ios - "Invalid Binary"iTunes 连接 (Swift 2)

ios - 设置UIButton共享快速操作图标

ios - 无法在 Xcode 中启用健康记录功能

ios - 如何在iOS应用中检测音频文件的BPM

ios - 在 Swift 中通过 Promise 传递值