Sebbe Sebbe - 4 months ago 15
Swift Question

Add data/rows to UITableView within ViewController. Swift

How do I populate a UITableView Within a UIViewController?
The UITableView is dynamic and uses prototype cells.

(Using Swift)

This is what I have

Answer

Do following :

import UIKit

class tableViewOne: UIViewController{

    @IBOutlet var tableView: UITableView!
    // your data
    var dummyData = ["data 0","data 1","data 2"]

    override func viewDidLoad() {
        super.viewDidLoad()

    }

}

extension tableViewOne: UITableViewDataSource, UITableViewDelegate {
    // Define no of rows in your tableView
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dummyData.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // Default cell
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell

        cell.textLabel!.text = dummyData[indexPath.row]

        return cell;
    }

}

Note: Don't forget to setup DataSource and Delegate of UITableView in the storyboard. No need to define programmatically if already defined in storyboard.