Search code examples
swiftuitableviewcelliboutletcustom-cell

IBOutlets in UITableView Static Cells


I created a UITableView (and related classes), with two sections:

  • the first one is a static custom cell
  • the second one is a prototype cell

To control the static cell, I implement a class, and in that class I added IBOutlet to an object (for example label) in the static cell. When I attempt to access that outlet in the class controlling the table view, I get this error:

outlet doesn't exist

I made a video, for explain better my problem.


Solution

  • Short version

    UITableView cannot be at the same time a Static Cells and a Dynamic Prototypes content. You need to pick one or the other.

    Because you need Dynamic Prototypes, use Dynamic Prototypes.


    Long version

    Steps to create Dynamic Prototypes:

    1. Select your Table View in IB > Show Attributes Inspector > Table View > Content > Dynamic Prototypes
    2. From the section IB > Show the Object Library, drag as many Table View Cell onto your table view as you have cell types.
    3. If you have some cells that never change at run time, you can very well create 1 instance of each right there in IB ; they will behave like Static Cells
    4. For the custom cells(†), the recommended practice is to create subclasses of UITableViewCell, and apply that custom class to the relevant cell or cells (IB > Show the Identity Inspector), and pick your Custom Class from the list. This of course implies you have created such sub-classes.
    5. Do not forget to assign a unique identifier to each cell prototype, so that you can retrieve these at runtime using dequeueReusableCellUsingIdentifier;

    With this setup, you can select your Table View Cell, IB > Show Assistant Editor, and control-drag references in your custom class. You may need to tell the Assistant Editor which file to pick.


    (†) There are plenty of other ways to do this ; all outside of the scope of this response.