子类化从 xib 创建的自定义视图

Posted

技术标签:

【中文标题】子类化从 xib 创建的自定义视图【英文标题】:Subclassing a custom view that was created from a xib 【发布时间】:2015-08-24 17:31:13 【问题描述】:

我使用 xib (MyCustomCell.xib) 创建了一个自定义 UICollectionViewCell(我们称之为 MyCustomCell),我想创建一个 MyCustomCell 的子类(我们称之为 MyCustomCell2)。 MyCustomCell2 (MyCustomCell) 的父级有一个名为 titleLabel 的 IBOutlet。但是,即使我这样做了,MyCustomCell2 的 titleLabel 也总是返回 nil

    self.collectionView.
            registerClass(MyCustomCell2.self, forCellWithReuseIdentifier: cellIdentifier); 

在 viewDidLoad 中

    let cell = collectionView.
       dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! MyCustomCell2;

在 cellForRowAtIndexPath 中

有什么想法吗?

【问题讨论】:

【参考方案1】:

首先,当您使用registerClass 时,您的插座无法连接。您需要使用registerNib

其次,需要在您正在加载的 xib 中连接插座。如果您正在加载子类的 xib,则需要在其中连接插座。

【讨论】:

但是 MyCustomCell 的 cellIdentifier 与 MyCustomCell2 不同,所以 registerClass:cellReuseIdentifier 不会导致崩溃吗? @user3808735 你需要使用 registerNib。并且您需要注册连接插座的笔尖

以上是关于子类化从 xib 创建的自定义视图的主要内容,如果未能解决你的问题,请参考以下文章