Reputation: 12278
In a normal storyboard, table views come "with" embedded cells. Simply set "Dynamic Prototypes" to 1 (or more):
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.)
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
Reputation: 12278
In current (2020) Xcode there's no direct button to create a table view cell -style XIB file.
The secret is
create a 'Cocoa Touch Class', select UITableViewCell
and ALSO select 'create XIB file'
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.)
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")
}
And that's how you do it.
New file - cocoa touch class - subclass of table cell - do select 'also create XIB file'
In viewDidLoaed, register the XIB file using,
The file name (no suffix) and the identifier
You're done, you can now refer to the cell in the normal way in dequeueReusableCell
Upvotes: 4