iOS Swift 4 Coding

How to re-use a TableViewCell layout in Xcode 10 with Swift?

2 views October 17, 2018 October 17, 2018 bicobro 0

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:

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

Was this helpful?