在 UICollectionViewCell 类中有几个关于 nil outlet 的帖子,例如 this和 this ,但没有一个解决方案有效。使用强导出而不是弱导出失败,registerClass
解决方案不适用,因为单元不使用自定义 XIB,数据源和委托(delegate)正确连接等。
在这种情况下,outlet 是一个 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
为 nil,但 UICollectionView 类内部的圆角成功,因此 imageView
看起来确实已连接。
为什么 imageView
在 UICollectionViewCell 类中为 nil?
最佳答案
您可能想尝试在 awakeFromNib
中调用 doInit
但是我认为框架可能还没有初始化 (虽然没有测试):
override func awakeFromNib() {
super.awakeFromNib()
doInit(frame)
}
由于您想根据 View 的框架更新 cornerRadius
,我会在 layoutSubviews
中执行此操作,因此任何框架更改都将直接反射(reflect)到角半径值:
override func awakeFromNib() {
super.awakeFromNib()
imageView.layer.masksToBounds = true
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.layer.cornerRadius = frame.size.width / 2
}
更新:既然你说过,你不使用 nib 文件来加载 View ,只需将 imageView.layer.masksToBounds = true
移动到 init(frame: CGRect)
并删除 awakeFromNib
。
关于ios - UICollectionViewCell socket 在类中为 nil 但在使用 dequeueReusableCellWithReuseIdentifier 后工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36390800/