Creating the table-view cell subclass

To create a new UITableViewCell subclass, you need to create a new file (File | New | File) and choose a Cocoa Touch file. Name the file ContactTableViewCell and select UITableViewCell as the superclass for your file, as shown in the following screenshot:

When you open the newly-created file, you'll see that two methods were added to the ContactTableViewCell for you. These methods are awakeFromNib() and setSelected(_:animated:). The awakeFromNib() method is called the very first time an instance of your class is created. This method is the perfect place to do some initial setup that should only be performed once for your cell.

The second method in the template is setSelected(_:animated:), you can use this method to perform some customizations for the cell when a user taps on it. You could, for instance, change the text or background color for a cell there. For now, delete both methods from the class and replace its contents with the following code:

@IBOutlet var nameLabel: UILabel!
@IBOutlet var contactImage: UIImageView!

The preceding code should be the entire body for the ContactTableViewCell class. The variables in the class are annotated with @IBOutlet; this means that those variables can be connected with your prototype cell in Interface Builder. To do this, open Main. storyboard, select your prototype cell and look for the Identity Inspector in the sidebar on the right. Set the class property for your cell to ContactTableViewCell, as shown in the following screenshot. Setting this makes sure that your layout and code are correctly connected:

Next, select the table view cell that you added to the table view. Open the Connections Inspector in the right sidebar. Under the Outlets header, you'll find a list of names. Among those names, you can find the nameLabel and contactImage you added to ContactTableViewCell. Drag from the circle next to the nameLabel towards the label inside of your cell. By doing this, you connect the @IBOutlet that was created in code to its counterpart in the layout. Perform the same steps outlined in the preceding paragraph for the image, as shown in the following screenshot:

The last step is to provide a reuse-identifier for your cell. The table view uses the reuse-identifier so it can reuse instances of table-view cells. Cell-reuse is an optimization feature that will be cover in depth later in this chapter.

To set the reuse-identifier, open the Attributes inspector after selecting your cell. In the Attributes inspector, you'll find, and an input field labeled Identifier. Set this field to the ContactTableViewCell value.

With your layout fully set up, we need to take a couple more steps to make the table view show a list of contacts by assigning it a data source and delegate.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset