Wednesday 11 June 2014

UITableView Demo using Swift

Hi All,  Apple has introduced new programming language called "Swift" and iOS 8. Hope all of you know about this. I have downloaded XCode 6.0 beta from "developer.apple.com" and started playing with it. I have created a UITableView demo and thought of sharing it with you.

I have created a empty application and created new UIViewController subclass "TableViewController" and corresponding xib file called "TableView".


Added code in AppDelegate.swift to create a new navigation controller with TableViewController as root view controller :

        var tableVC : TableViewController = TableViewController(nibName: "TableView", bundle: NSBundle.mainBundle())
        var navVC : UINavigationController = UINavigationController(rootViewController: tableVC)
        

        self.window!.rootViewController = navVC

now, func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool of AppDelegate class will look like below :

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        var tableVC : TableViewController = TableViewController(nibName: "TableView", bundle: NSBundle.mainBundle())
        var navVC : UINavigationController = UINavigationController(rootViewController: tableVC)
        
        self.window!.rootViewController = navVC
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()
        
        return true
    }

In TableViewController class, I took elements as an optional array and implemented UITableViewDatasource methods :

    import UIKit

class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
    var elements : Array<AnyObject>?
    
    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        self.title = "Table View"
        
        elements = ["One","Two","Three","Five","Six","Seven","Eight","Nine","Ten"]
    }
    
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
    {
        return elements!.count;
    }
    
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
    {
        var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell!
        
        if cell == nil
        {
            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
        }
        
        cell.textLabel.text = elements![indexPath.row] as String
        
        return cell
    }
}

Here is the output :



Here is the Source Code.