Tuesday, March 20, 2018

UITableView using custom .xib files for table and cells.

Occasionally I find myself needing a UITableView that has been setup from a custom .xib (interface builder) file, rather than from within a Storyboard.  The process for setting up a UITableView within an xib is different to that for setting one within a Storyboard, mainly because you cannot use prototype cells and design your cells within the UITableView itself - the custom cell requires its own .xib file too.  Ive documented the process for setting up a UITableView in this way below.

First up, I assume you have a UIViewController that is within an .xib file.  If not, theres a guide to setting up a UIViewController within an xib here.  You can also use the below method for a UITableView within a storyboard - you just need to delete the UITableViewCell from within the UITableView first.


  • Drag in a new UITableView object into your UIViewController
  • Drag datasource and delegate outlets onto Files Owner
  • Drag an outlet connection for the UITableView into your UIViewController
  • Create a new .xib file to hold the custom cell
  • Delete any view in that file and add a new UITableViewCell object.
  • Add a new swift file to contain your custom cell UITableViewCell subclass, and define the basic class
  • Back in the custom cell .xib file, set the Custom Class of the UITableViewCell object to the sub-class you just defined.
  • Then in the same xib file, but this time on the Attributes Inspector rather than the Identity Inspector, set the Re-use Identifier to something memorable - I usually just use that class name again.
  • Now back in the main UIViewController swift that contains the UITableView,  add a line of code to register the custom nib you've just set up.  Somewhere on initialization is good, such as viewDidLoad.  Re-use identifier should match the 'RestorationId' property set in the cells custom xib file.  


  • Now add the basic stub functions for UITableViewDataSource.  You can see how the custom cell is dequeued in the code below. The identifier mentioned there is the one we set in the custom cell as 'RestorationId'.

  • Thats all the basic setup done.  From here you can add any UI elements you wish into the custom cell xib file, and drag the properties over to the swift file for your custom UITableViewCell class.  Then within the 'cellForRowAtIndexPath' you can set and populate those properties.

No comments:

Post a Comment

Social Network with Firebase 3 - Infinitely scrolling UITableView of Firebase Items

Ive already talked about the basics of a Firebase social network project , and adding posts in two other articles. Here I want to explain ...