Thursday, June 12, 2014

Swift - Simple TableView Programmatically

Here's a simple example in Swift, of programmatically (no .xib files) creating a UITableViewController that presents a UIViewController with a "Dismiss" button. This is simple code but I've been trying to get comfortable using Swift to do some common tasks. Along the way, I'm discovering some interesting and sometimes quirky things about Swift.

For brevity, I'm only showing the '...didFinishLaunching...' function in the AppDelegate.swift file. I set the 'rootViewController' to my 'ListViewController' and we're off and running.

I use a minimal amount of code to instantiate the UITableViewController, starting with a .swift file that only inherits from NSObject then changing the superclass to UITableViewController once the file is created. I learned this from the Big Nerd Ranch books as a way to understand what goes on under the hood. In a real app, the 'didSelectRowAtIndexPath' would have some sort of selection for different view controllers. In this example, you'll get the one and only 'DetailViewController'.

The 'DetailViewController' is also created with a minimal amount of code and changing the superclass to UIViewController once the file is created. If you are building for arm-64, you don't have to explicitly type 'btnWidth' and 'btnHeight' to CGFloat However, the compiler will complain if you try to build this for 32-bit architecture without explicitly typing these constants as CGFloat. I think this is the preferred way to deal with type mismatches in Swift. I've been finding some discussions about this online and would be interested in hearing others' feedback on this.

Enjoy!


//
//  AppDelegate.swift
//  SwiftDemo
//
//  Created by Tom Limbaugh on 6/3/14.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
                            
    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // Override point for customization after application launch.
        self.window!.rootViewController = ListViewController(style: .Plain)
        self.window!.backgroundColor = UIColor.whiteColor()
        self.window!.makeKeyAndVisible()
        return true
    }

}



//
//  ListViewController.swift
//  SwiftDemo
//
//  Created by Tom Limbaugh on 6/3/14.
//

import UIKit

class ListViewController: UITableViewController {
    
    override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        
        var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("UITableViewCell") as? UITableViewCell
        
        if !cell {
            cell = UITableViewCell(style: .Default, reuseIdentifier: "UITableViewCell")
        }
        
        switch indexPath.row {
            
        case 0:
            cell!.textLabel.text = "Item 1"
        case 1:
            cell!.textLabel.text = "Item 2"
        case 2:
            cell!.textLabel.text = "Item 3"
        default:
            cell!.textLabel.text = ""
        }
        return cell as UITableViewCell
    }
    
    override func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        
        var dvc = DetailViewController(nibName: nil, bundle: nil)
        
        presentViewController(dvc, animated: true, completion: nil)
    }
   
}




//
//  DetailViewController.swift
//  SwiftDemo
//
//  Created by Tom Limbaugh on 6/3/14.
//


import UIKit

class DetailViewController: UIViewController {
    
    init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
        super.init(nibName: nibName, bundle: nibBundle)
        
        self.view.backgroundColor = UIColor.redColor()
        
        let viewFrame: CGRect = UIScreen.mainScreen().bounds
        let btnWidth:CGFloat = 100.0
        let btnHeight:CGFloat = 50.0
        
        let dismissButton:UIButton = UIButton(frame: CGRectMake((viewFrame.width / 2) - (btnWidth / 2), (viewFrame.height / 2) - (btnHeight / 2), btnWidth, btnHeight))
        
        dismissButton.backgroundColor = UIColor.yellowColor()
        dismissButton.setTitle("Dismiss", forState: .Normal)
        dismissButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
        dismissButton.addTarget(self, action: "tappedButton:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(dismissButton)
    }
    
    func tappedButton(sender:UIButton!) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}


No comments:

Post a Comment