连接的 IBOutlets 未初始化 [英] Connected IBOutlets are not initialized

查看:48
本文介绍了连接的 IBOutlets 未初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 Swift 中实现了自定义 UICollectionViewCell 类,使用 UICollectionViewCotroller 创建了故事板,分配了我的自定义控制器类、自定义单元类、单元 id 等......基本上是让 UICollectionViewController 工作所需的一切.

I've implemented custom UICollectionViewCell class in Swift, created storyboard with UICollectionViewCotroller, assigned my custom controller class, custom cell class, cell id etc... Basically everything required to make UICollectionViewController work.

在故事板单元原型中,我添加了一些视图并将它们作为 IBOutlets 连接到我的自定义单元类:

In storyboard cell prototype I've added few views and connected them as IBOutlets to my custom cell class:

这里是我的 IBOutlets 代码(如您所见,它们已连接):

here my IBOutlets in code (as you can see, they are connected):

我也在我的控制器中注册了自定义单元类:

I registered custom cell class in my controller too:

self.collectionView.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

当我在代码中将单元格出列时,它返回我自定义类型的单元格,但两个 IBOutlets 都未初始化(等于 nil)

When I dequeue my cell in code it returns cell of my custom type but both IBOutlets aren't initialised (equal nil)

    let cell = collectionView?.dequeueReusableCellWithReuseIdentifier(reuseIdentifier,
    forIndexPath: indexPath) as MyCollectionViewCell

    if let path = indexPath {
        // Crash here as imageView is nil
        cell.imageView.image = imagesArray[path.item] 
    }

崩溃日志:

fatal error: unexpectedly found nil while unwrapping an Optional value

如果我在上面的 if 语句上放置断点并执行 po cell 我有这个输出:

if I put breakpoint on if statement above and do po cell I have this output:

(lldb) po cell
0x00007fa799f4cdf0
 {
  UIKit.UICollectionViewCell = {
    UIKit.UICollectionReusableView = {
      UIKit.UIView = {
        UIKit.UIResponder = {
          ObjectiveC.NSObject = {}
        }
      }
    }
  }
  selectionView = nil
  imageView = nil
}

为什么 IBOutlets 没有被初始化?

Any ideas why IBOutlets aren't initialised?

推荐答案

发生这种情况是因为 IBOutlets 是在 initWithCoder 完成后才连接的.

It happens because IBOutlets are connected later, after initWithCoder has finished.

要在连接后设置控件,您可以在 UIColletionViewCell 子类中覆盖 - applyLayoutAttributes:.

To setup your controls after they've been connected, you can override - applyLayoutAttributes: in your UIColletionViewCell subclass.

override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes) {
    setupControls()
}

根据文档,它是一个空方法,旨在被覆盖以便将自定义布局属性应用于视图.听起来是对的.

According to documentation, it's an empty method, meant to be overridden in order to apply custom layout attributes to the view. Sounds about right.

这篇关于连接的 IBOutlets 未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆