Sometimes you need to re-use a TableViewCell layout in multiple ViewControllers. In this knowledge base article is explained how to realize re-use of a UITableViewCell in a simple way:
- Create a code file for the TableViewCell code:
- Choose “New File” in Xcode and select “Cocoa Touch Class”
- Set a name for the new file in the “Class” field. We use “MyReusableTableViewCell.swift”.
- Select “UITableViewCell” in the “Subclass of” field.
- Click “Next”
- Create a layout file for the TableViewCell:
- Choose “New File” in Xcode and select “View” under the “User Interface” section. We use “MyReusableTableViewCell.xib”.
- Open the new file.
- Select the TableViewCell root.
- In the Identity Inspector set as class the code file you created above
- In the Attributes Inspector (at the right) set the Size property to FreeForm.
- Resize the view to a regulare TableViewCell size (any you like)
- Place the views you need (e.g. labels etc…)
- Add the TableViewCell in a ViewController
- Open the TableCellViewController or ViewController where you want to use the new TableViewCell.
- Add the following code to the ViewController viewDidLoad function:
-
tableView.register(UINib(nibName: "MyReusableTableViewCell", bundle: nil), forCellReuseIdentifier: "MyReusableTableViewCellIdentifier")
-
- From here you can use the reusable TableViewCell as you used to be.