【问题标题】:Swift - How to inherit from a custom cell that's tied to a xib fileSwift - 如何从绑定到 xib 文件的自定义单元格继承
【发布时间】:2016-12-05 13:58:46
【问题描述】:

我有一个名为 NormalImageCell 的自定义单元格,它继承自 UITableViewCell 并绑定到 xib。假设我想创建一个名为 LargeImageCell 的新单元格,它继承自 NormalImageCell 而不创建全新的 xib。我可以在没有界面生成器的情况下以编程方式轻松完成此操作,但由于 NormalImageCell 绑定到 xib 并且 xib 中的单元格只能连接到一个自定义类和一个重用标识符,我怎么能将其用于 LargeImageCell 吗?

这在没有 Interface Builder 的情况下工作。

class LargeImageCell: NormalImageCell {...}

tableView.registerClass(NormalImageCell.self, forCellWithReuseIdentifier: NormalImageCell.id())
tableView.registerClass(LargeImageCell.self, forCellWithReuseIdentifier: LargeImageCell.id())

这会导致 Interface Builder 崩溃:

tableView.registerNib(NormalImageCell.nib(), forCellWithReuseIdentifier: NormalImageCell.id())
tableView.registerNib(LargeImageCell.nib(), forCellWithReuseIdentifier: LargeImageCell.id())

顺便说一句,我正在声明这样的 nib 和 id 方法:

class NormalImageCell: UITableViewCell {

    class func id() -> String {
        return String(self)
    }

    class func nib() -> UINib { 
        return UINib(nibName: String(self), bundle: nil) 
    }
}

class LargeImageCell: NormalmageCell {
    ...
}

【问题讨论】:

  • 你如何声明你的nib 方法?
  • 类 func nib() -> UINib { return UINib(nibName: String(self), bundle: nil) }
  • 您的项目中是否有两个 nib 文件:NormalImageCell.xib 和 LargeImageCell.xib ?
  • 我只有 NormalImageCell.xib。我不想为 LargeImageCell 创建另一个 xib,因为这两个单元格几乎相同,只有 imageView 大小不同。我正在尝试通过继承来重用 NormalImageCell,这样我就不必复制任何 xibs/代码。
  • 我不想为 LargeImageCell 创建另一个 xib 那你就做不到。

标签: swift inheritance cell xib nib


【解决方案1】:

您应该从主包中检索笔尖,例如:

class func nib() -> UINib {     

   return UINib(nibName: String(self), bundle: NSBundle.mainBundle())
}

【讨论】:

    【解决方案2】:

    所以有一个解决方案,但它确实使您的数据源有点复杂。

    1. 创建您的对象LargeImageCell,但不要给它任何子类型。
    2. 在初始化程序中添加 NormalImageCell 作为参数以及任何其他信息。
    3. 配置NormalImageCell 并将其设置为在您的对象上具有属性。
    4. 在您的数据源中,将 NormalImageCell 出列并用它初始化您的对象 LargeImageCell
    5. 返回新配置的单元格。

    不是最好的选择,但它适用于笔尖单元上的扩展功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-10
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多