【问题标题】:In which method of a UICollectionViewCell should I write code to only run once?我应该在 UICollectionViewCell 的哪个方法中编写代码只运行一次?
【发布时间】: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 方法的工作。
  • 我没有将whiteViewimgView 添加到单元格(将在Interface Builder 中创建)。我正在创建这些以创建两者的组合视图并将其添加为图像。将其添加为图像很重要,因为它受益于 tvOS 上的特殊动画。我不想在 Interface Builder 中创建它们。

标签: ios swift swift2 uicollectionviewcell


【解决方案1】:

很遗憾,我不知道您是如何创建单元格的,但是: 如果您将自定义单元格类注册到您的 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)
    }

【讨论】:

    【解决方案2】:

    awakeFromNib() 方法只被调用一次,所以你在这里设置你的单元格,比如:-

    class YourCollectionViewCell: UICollectionViewCell {
    
        override func awakeFromNib() {
            super.awakeFromNib()
    
           //do some work here that needs to happen only once, you don’t wanna change them later.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多