Friday, September 5, 2014

UITableView

Here is how to create a simple table view with Swfit and the storyboard:

1. Drag a table view in the storyboard

2. In the Connections Inspector, link the dataSource and delegate outlets to View Controller.

3. Add UITableViewDelegate and UITableViewDataSource protocols in ViewController.swift

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
....
}

where
UIViewController = super class (before the first protocol)
UITableViewDelegate = first protocol
UITableViewDataSource = second protocol

Note: the warning occurs because cellForRowAtIndexPath and numberOfRowsInSection are required.

4. Add an array to be printed in the table

let myArray = ["AAA", "BBB", "CCC"]

5. Set the number of rows

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


6. Set the table content

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = UITableViewCell(style: UITableViewCellStyle.Value2, reuseIdentifier: nil) cell.textLabel.text = myArray[indexPath.row] return cell }

**********************
UITableView without using the Storyboard

No comments:

Post a Comment