In this video tutorial I am going to share with you how to create a UISegmentedControl with three tabs which will allow user to switch between three different list of elements: Private, Protected and Public. The list of elements displayed in each tab is stored in an Array created within the same UIViewController.
If you would like to learn how to load list of items from a remote PHP script, watch this tutorial: UISegmentedControl with UITableView example in Swift. Part 2..
Source code:
import UIKit class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate { @IBOutlet weak var mySegmentedControl: UISegmentedControl! @IBOutlet weak var myTableView: UITableView! let privateList:[String] = ["Private item 1","Private item 2"] let friendsAndFamily:[String] = ["Friend item 1","Friend item 2", "Friends item 3"] let publicList:[String] = ["Public item 1", "Public item 2", "Public item 3", "Public item 4"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var returnValue = 0 switch(mySegmentedControl.selectedSegmentIndex) { case 0: returnValue = privateList.count break case 1: returnValue = friendsAndFamily.count break case 2: returnValue = publicList.count break default: break } return returnValue } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let myCell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) switch(mySegmentedControl.selectedSegmentIndex) { case 0: myCell.textLabel!.text = privateList[indexPath.row] break case 1: myCell.textLabel!.text = friendsAndFamily[indexPath.row] break case 2: myCell.textLabel!.text = publicList[indexPath.row] break default: break } return myCell } @IBAction func refreshButtonTapped(sender: AnyObject) { myTableView.reloadData() } @IBAction func segmentedControlActionChanged(sender: AnyObject) { myTableView.reloadData() } }