简体   繁体   English

当在Storyboard中的UITableView中具有带有静态单元格的XIB自定义单元格时,插座为零

[英]Outlets are nil when having custom cell with XIB in UITableView in Storyboard with static cells

I want to use static cells in a UITableView in my storyboard. 我想在情节UITableView中使用静态单元格。 But also I want those cells to be loaded from a custom .xib file with a custom UITableViewCell subclass. 但是我也希望这些单元格从带有自定义UITableViewCell子类的自定义.xib文件加载。

I want to do this because I want to reuse the cells in multiple table views. 我想这样做是因为我想在多个表视图中重用单元格。

So I added some static cells in storyboard and set the custom class in the identity inspector. 因此,我在情节提要中添加了一些静态单元格,并在身份检查器中设置了自定义类。

But when I want to access the Outlets in the custom view's awakeFromNib method, they are nil . 但是,当我想在自定义视图的awakeFromNib方法中访问Outlets时,它们为nil Even later, they're not beeing instantiated. 甚至以后,它们也不会实例化。

How can I do this the right way? 我该如何正确地做呢?

If you are adding static cells in the storyboard, they are functioning like separate .xib files and overriding the custom .xib s you are willing to use. 如果要在情节.xib中添加静态单元格,则它们的功能类似于单独的.xib文件,并覆盖您愿意使用的自定义.xib

You should use dynamic cells in your table view if you want to reuse your cells in multiple table views. 如果要在多个表视图中重复使用单元格,则应在表视图中使用动态单元格。 Dynamic cells are usually more sustainable as well, especially in a larger application. 动态单元通常也更可持续,特别是在较大的应用程序中。

Ok I figured it out, how this is possible: 好吧,我想通了,这怎么可能:

I created a container class for my UITableViewCell as it is described in this answer: https://stackoverflow.com/a/34881072/4846592 我为UITableViewCell创建了一个容器类,如以下答案中所述: https : //stackoverflow.com/a/34881072/4846592

This class contains a property to get access to the custom cell and loads the XIB in its initializer 此类包含一个属性,可以访问自定义单元并将XIB加载到其初始化程序中

Here's the code for Swift 3 这是Swift 3的代码

class CustomTableViewCellContainer: UIView {    
var cell: CustomTableViewCell!

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

        cell = Bundle.main.loadNibNamed("CustomTableViewCell", owner: self, options: nil)!.first as! TextFieldTableViewCell
        cell.frame = self.bounds
        cell.autoresizingMask = [.flexibleWidth]
        self.addSubview(cell)
    }
}

Then, I just added a UIView into the ContentView of a static UITableViewCell in the Storyboard and set the height and CustomTableViewCellContainer as custom class name. 然后,我只是将一个UIView添加到情节提要中的静态UITableViewCell的ContentView中,并将height和CustomTableViewCellContainer设置为自定义类名称。 Finally I added an IBOutlet to it to get access to the custom cell. 最后,我向其中添加了IBOutlet以访问自定义单元。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM