Tag Archives: xcode 6

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.