Monday, 20 October 2014

How to make a tableview using Swift

In this blog I am creating a simple tableView with details. Hope this will help you when you will be creating such a table in you code using swift for the first time.


1. Create new xcode project and select project type as simple view application

 2. Name as per your choice in my case it is SwiftTableViewDemo, language as swift and device as iPhone. No need to select Core Data.
3. Click create to create this project.
4. Go to Main.Storyboard and add UTableView in it from the right side pane. This is how it looks like

5. Click on TableView with ctrl key and drop the pin on View controller and one by one do it for both delegate and data source. Make connections as shown in image
         
6. Select table view in main.storyboard and do settings

(a) Set number of prototype cells to 1
(b)  Now select UITableViewCell and set "cell" as Reuse Identifier.

7. Now go to ViewController.swift class. Add UITableViewDelegate, UITableViewDataSource along with UIViewController in class seperating them by ,.
8. Now is the time to implement table view's delegate methods.
9. Declare following two variables
  @IBOutlet var tableView: UITableView!              (also make connection of this var with table view)
  var data: [String] = ["one","two","three","four"]

10. Add following methods to it 

 func numberOfSectionsInTableView(tableView: UITableView) -> Int
 {
        return 1
 }
    
 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
 {
        return self.data.count
 }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
        var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
        cell.textLabel?.text = self.data[indexPath.row]
        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!)
    {
        println("You clicked cell number #\(indexPath.row)!")
    }


11. Now run this code. If all gone well you will see below output in your simulator (or can be on your device)


Now you are done with simple table view using Swift. Thanks for viewing. 

Please share if you see this is useful to you.

3 comments:

  1. Name as per your choice in my case it is SwiftTableViewDemo, language as swift and device as iPhone. No need to select Core Data. Spy Facebook Instant Messenger

    ReplyDelete
  2. Enjoyed reading through this, very good stuff, thank you.
    iphone apps design

    ReplyDelete
  3. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me. whocall

    ReplyDelete