UICollectionViewCell出口nil在类中但在使用dequeueReusableCellWithReuseIdentifier

时间:2016-04-03 20:32:29

标签: ios swift uiimageview uicollectionview uicollectionviewcell

UICollectionViewCell类中的nil个出口有几个帖子,如thisthis,但没有一个解决方案有效。使用强插座而不是弱插座失败,registerClass解决方案不适用,因为单元不使用自定义XIB,数据源和代理连接正确等等。

在这种情况下,插座是UIImageView,在UICollectionViewCell类中访问时为nil,但在外部访问时工作正常。

UICollectionView代码:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(AlbumCellIdentifier, forIndexPath: indexPath) as! AlbumCell

    cell.imageView.image = getThumbnail()
    cell.imageView.contentMode = .ScaleAspectFill        
    cell.imageView.layer.masksToBounds = true
    cell.imageView.layer.cornerRadius = cell.frame.size.width / 2

    return cell
}

UICollectionViewCell代码:

class AlbumCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!

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

        doInit(frame)
    }


    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        doInit(frame)
    }


    private func doInit(frame: CGRect) {
        // Round corners
        imageView.layer.masksToBounds = true
        imageView.layer.cornerRadius = frame.size.width / 2
    }
}

UICollectionViewCell类内的圆角失败,因为imageView为零,但UICollectionView类内的圆角成功,因此imageView似乎已连接。

为什么imageView在UICollectionViewCell类中没有?

1 个答案:

答案 0 :(得分:3)

您可能想尝试在doInit中调用awakeFromNib但是我认为该框架可能尚未初始化(虽然没有测试)

override func awakeFromNib() {
  super.awakeFromNib()
  doInit(frame)
}

由于您要根据视图的框架更新cornerRadius,我会在layoutSubviews中执行此操作,因此任何帧更改都将直接反映到角半径值:

override func awakeFromNib() {
  super.awakeFromNib()
  imageView.layer.masksToBounds = true
}

override func layoutSubviews() {
  super.layoutSubviews()
  imageView.layer.cornerRadius = frame.size.width / 2
}

更新:由于您说过,您不使用nib文件加载视图,只需将imageView.layer.masksToBounds = true移至init(frame: CGRect)并删除awakeFromNib

相关问题