Hi Friends, Earlier we learnt how to create tableView in iOS using objective C. Today we

will learn how to create a simple tableView in iOS using Swift.

Steps:

  1. create a new Xcode Project  in Swift and lets say SimpleTableViewSwift.
  2. Now go to your storyBoard and drag a tableView and connect dataSource and delegate and IBOutlet.

 

screen-shot-2016-09-19-at-1-24-21-am3. Now go to your ViewController.m and and define dataSource and delegate Method for the tableView .

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

  let tableData = [“Ram”,“Shyam”,“Nilesh”]

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

    // MARK: TableView DataSource and delegate Methods

    

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.tableData.count

    }

    

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

    

    let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:“cell”)

     cell.textLabel?.text = tableData[indexPath.row]

    

    return cell

    }

    

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        print(“You tapped cell number \(indexPath.row).”)

    }

}

4. Now run the code and see the desired output.

Please do like and share your reviews.

You can download the whole project from here.

Advertisements