UIViewController and UITableView in Swift

I originally wrote this post back when Swift 1.0 came out. Since then Apple has released several new version of Swift with new syntax. I’ve updated this post accordingly – Bay 11/13/2015

I’m just starting to play around with the newly announced programming language, Swift.

So far it’s a bit tricky to get used to the new syntax simply because when I first started writing Objective-C I had to learn some of its funky behaviors and nuances. Swift reverses a lot of those decisions and brings it inline with more modern languages.

To get started with Swift, aside from playing around in a Playground with it, I’ve decided to just start rewriting basic controls that I’m familiar with in Objective-C. To start, I rewrote what is a super basic UIViewController with a UITableView as a subview, displaying its contents.

(all code snippets are in Swift, don’t mind them being labeled as Objective-C)

class DumbTableViewController: UIViewController, UITableViewDataSource {
}

Let’s declare our data source.

var items: [Int] = [Int]()

Next we implement the viewDidLoad method that we’re so familiar with but this time we’re “overriding” it.

    override func viewDidLoad()  {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.whiteColor()
        
        // Loop through 0 and 100 (including 100)
        // and append it to our datasource
        (0...100).map({ items += value })
        
        // Create our UITableView with our view's frame
        var tableView: UITableView = UITableView(frame: self.view.frame)

        // Register our cell's class for cell reuse
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")

        // Set our source and add the tableview to the view
        tableView.dataSource = self
        self.view.addSubview(tableView)
    }

Implement the two required methods in the UITableViewDataSource protocol:

    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

 

    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        // dequeue a cell for the given indexPath
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
        
        // set the cell's text with the new string formatting
        cell.textLabel.text = "\(items[indexPath.row])"
        
        return cell
    }

And that’s it! Now we have a UITableView displaying 0 – 100. Not that useful, but it allows us to start seeing what was familiar with Objective-C in a new light.

The full code source can be found at this Gist.

4 thoughts on “UIViewController and UITableView in Swift”

  1. array of Ints
    Objective-C
    1var items: Int[] = []
    for value in 0…100 { items += value }

    It doesn’t work, instead use array.append()

  2. hi, i use swift create a view it has a uiview and a table view called mycountViewController. and i want click the mycountViewController view link to another view. however, i must click the cell twice to go the another view, do you know why?
    this is my code:

    import UIKit

    import CoreData

    class mycountViewController:UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var mygpsview: UITableView!

    var runs = [NSManagedObject]()

    override func viewDidLoad() {

    super.viewDidLoad()

    mygpsview.delegate = self

    mygpsview.dataSource = self

    let appdelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let context:NSManagedObjectContext = appdelegate.managedObjectContext

    do{

    let request = NSFetchRequest(entityName: “Run”)

    let result = try context.executeFetchRequest(request) as? [NSManagedObject]

    if let runsdata = result {

    runs = runsdata

    }

    }catch{

    }

    }

    override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()

    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 1

    }

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

    return runs.count

    }

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

    let cell = mygpsview.dequeueReusableCellWithIdentifier(“Cell”) as! contCellTableViewCell

    let run = runs[indexPath.row]

    let distancekm = run.valueForKey(“distance”)

    let dist = distancekm as! Double

    let a = dist / 1000.0

    let astr = NSString(format: “%.2f”, a)

    let duratation = run.valueForKey(“duration”)

    let du = duratation as! Int

    let (h,m,s) = secondToHourMinSecond(du)

    let hh = NSString(format: “%.2d”, h)

    let mm = NSString(format: “%.2d”, m)

    let ss = NSString(format: “%.2d”, s)

    let coredate = run.valueForKey(“timestamp”)

    let date = coredate as! NSDate

    let calender = NSCalendar.currentCalendar()

    let components = calender.components([.Year,.Month,.Day],fromDate: date)

    let year = components.year

    let month = components.month

    let monthstr = NSString(format: “%.2d”, month)

    let day = components.day

    let daystr = NSString(format: “%.2d”, day)

    cell.ridedistance.text = “(astr)公里”

    cell.ridedate.text = “(year)-(monthstr)-(daystr)”

    cell.ridespend.text = “(hh):(mm):(ss)”

    return cell

    }

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

    let detailvc:mydetailViewController = self.storyboard?.instantiateViewControllerWithIdentifier(“mydetailgps”) as! mydetailViewController

    self.presentViewController(detailvc, animated: true, completion: nil)

    }

    func secondToHourMinSecond (seconds:Int) -> (Int,Int,Int) {

    return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60 )

    }

    }

Leave a Reply

Your email address will not be published. Required fields are marked *