How to make a simple tableview with iOS 8.2 and Swift 3.0


This is a step by step tutorial to add UITableView programmatically in Swift.

Create a new project 

   Open Xcode 8.2 and create a new project with "Single View Application" template.

Create Table View

Open default ViewController.swift file and add table view instance below class declaration

import UIKit

Add table view Delegate and DataSource

Add UITableViewDelegate and UITableViewDataSource separated by comma after UIViewController in class declaration.

class ViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet var table: UITableView!

Add items as an Array of Strings and set some values in table view
    
    var items: [String] = ["let's", "start", "Swift"]

    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        table = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.plain)
        table.delegate      =   self
        table.dataSource    =   self
        table.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        self.view.addSubview(table)

    }
After that we need to implement the required methods of UITableViewDelegate and UITableViewDataSource -

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return items.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        
        let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cell")
        cell.textLabel!.text = items [indexPath.row]
        return cell;
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        NSLog("You selected cell #\(indexPath.row)!")
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Comments

Popular posts from this blog

Parse JSON from a file and showing data into UITableView

Parse JSON from a URL and showing data into UITableView

iOS UIScrollView in UIView