Adding Custom Cells to a tableView

Customize the cell in our own style – instead of using default table view style, We need a new cell type, so we can add multiple images, and or text in different places.

Drag and drop Table View Cell from utility area on UITableView.

customtableviewcell_swift_3

 

Now add an image view and a label from utility area to your prototype cell and adjust their size to look something like this:

customtableviewcell_swift_4

 

Here I have changed the color of the label to brown and and changed its default text to Name(you can change it to what ever color you like).Also I have increased the number of lines to 2.

customtableviewcell_swift_6

 

Ok, lets add the class to UITableViewCell

Right click on the project group>>New>>Cocoa Touch Class and press next.

add class name, select its parent class and choose Swift as Language if not already selected.

Here I am naming my class as CustomTableViewCell, it should be subclass of UITableViewCell

 

customtableviewcell_swift_4

Press next, choose the location where you want to save this class and press create.

Your project navigator should look like this:

customtableviewcell_swift_5

 

Now, Select the prototype cell from view controller(in storyboard) and add CustomTableViewCell as its class in utility area Under identity inspector

customtableviewcell_swift_7

also add same name(CustomTableViewCell) as its identifier just to make it little less confusing, under attribute inspector.

customtableviewcell_swift_8

 

Now, Add two IBOutlet inCustomTableViewCell class one for image and another for the name of the wonder and connect it to the image and label in CustomTableViewCell in viewController.

Here I have named my UIImageView as imageVW and UILabel as lblName

 

customtableviewcell_swift_9

Our inCustomTableViewCell class will look like this.

We are almost done now, Go to the cellForRowAtIndexPath method and replace the code with below code.

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

var cell:CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier(“CustomTableViewCell”) as! CustomTableViewCell

cell.imageVW.image = UIImage(named:self.arrImageName[indexPath.row])

cell.lblName.text = self.tableData[indexPath.row]

return cell
}
..

 

Here, we have first created an object for CustomTableViewCell class using the cell identifier that we set earlier.

then, we have just added value to its variable and we are Done.

Leave a comment

Your email address will not be published. Required fields are marked *