Fattie
Fattie

Reputation: 12278

How do you make and use an XIB file for a table view cell, rather than just using a cell "in" the table view in storyboard?

In a normal storyboard, table views come "with" embedded cells. Simply set "Dynamic Prototypes" to 1 (or more):

enter image description here

You then use the those cells in your view controller simply with

...cellForRowAt

  let cell = tableView.dequeueReusableCell(
     withIdentifier:"YourCellClassID", for: indexPath) as! YourCellClass

Where YourCellClass is the class of the table view cell,

and the string "YourCellClassID" is just

the "Identifier" set in the Attributes Inspector (nowadays the **5th button)** of the storyboard.

(Be careful to NOT use the "restoration identifier" on the 4th button, identity inspector, which sounds the same but is unrelated.)

enter image description here

But what if you want to use an XIB file?

Instead of using one of the prototypes "in" the table view in storyboard?

If you use an XIB file, you can use the same cell in different tables.

How to do it?

Upvotes: 1

Views: 1688

Answers (1)

Fattie
Fattie

Reputation: 12278

Step 1, to make a cell-style XIB file

In current (2020) Xcode there's no direct button to create a table view cell -style XIB file.

The secret is

  1. create a 'Cocoa Touch Class', select UITableViewCell

  2. and ALSO select 'create XIB file'

enter image description here

enter image description here

You now have a cell-style XIB file, TesteCell.xib in the example.

(Feel free to delete TesteCell.swift if you don't need it.)

Step 2, add the register#UINib code in viewDidLoad

If you now try this:

let cell = tableView.dequeueReusableCell(
              withIdentifier: "TesteCellID",
              for: indexPath) as! TesteCell

In fact it does not work.

In viewDidLoad, you must add

override func viewDidLoad() {
    super.viewDidLoad()
    // We will be using an XIB file, rather than
    // just a cell "in" the table view on storyboard
    tableView.register(
        UINib(nibName: "filename without suffix", bundle: nil),
        forCellReuseIdentifier: "identifier in attributes inspector"
    )
}

In the example

override func viewDidLoad() {
    super.viewDidLoad()
    // We will be using an XIB file...
    tableView.register(
        UINib(nibName: "TesteCell", bundle: nil),
        forCellReuseIdentifier: "TesteCellID")
}

descrip

And that's how you do it.

Summary

  1. New file - cocoa touch class - subclass of table cell - do select 'also create XIB file'

  2. In viewDidLoaed, register the XIB file using,

  3. The file name (no suffix) and the identifier

  4. You're done, you can now refer to the cell in the normal way in dequeueReusableCell

Upvotes: 4

Related Questions