Create Table View in Swift

Today we are leaning how to create Simple Table view Using Swift!!!

Create New Project

Create NewProject with “Single Page Application” and select programming language as “swift”
(you can see in below image)

Screen Shot 2014-09-28 at 11.48.16 am

Add TableView Property

open the ViewController.swift Class and add new tableView instance varible below the Class declaration

@IBOutlet
var mytableView:UITableView

(Note: @IBOutlet attribute make the mytableView property visible in interface builder. )

Add TableView Delegate and Datasource protocols

To add protocol to viewController just add the UITableViewDelegate and UITableViewDataSource seprated by colons after UIViewController in class deleration, as you can see below

    
class ViewController: UIViewController, UITableViewDelegate , UITableViewDataSource {

....

}

After that we need to implement the  tableView(_:numberOfRowsInSection:),  tableView(_:cellForRowAtIndexPath:) and tableView(_:didSelectRowAtIndexPath:)  methods in the ViewController class and leave them empty for now

Add tableview in your ViewController

Screen Shot 2014-09-28 at 1.15.24 pm

Set the number of rows

    
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    return arrItems.count;
}

Create the cell

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{
        
   var cell:UITableViewCell  = self.mytableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
   cell.textLabel.text = arrItems[indexPath.row];
   return cell;
}

Setup Your Interface Builder

Screen Shot 2014-09-28 at 1.21.21 pm

 

You can Download Source Code From Here

Leave a comment