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. List of items displayed in each tab is loaded from a remote PHP script. I will include the source of PHP script below in this blog post.
If you would like to learn how to load list of items from a locally created(hard coded) array of elements, watch this video: UISegmentedControl with UITableView example in Swift. Part 1.
Source code of UIViewController:
import UIKit class ViewController: UIViewController, UITableViewDataSource,UITableViewDelegate { @IBOutlet weak var mySegmentedControl: UISegmentedControl! @IBOutlet weak var myTableView: UITableView! @IBOutlet weak var myActivityIndicator: UIActivityIndicatorView! var privateList:[String] = [] var friendsAndFamily:[String] = [] var publicList:[String] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) loadItems() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } internal 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 } internal 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) { loadItems() } @IBAction func segmentedControlActionChanged(sender: AnyObject) { switch(mySegmentedControl.selectedSegmentIndex) { case 0: if(privateList.count == 0) { loadItems() } else { myTableView.reloadData() } break case 1: if(friendsAndFamily.count == 0) { loadItems() } else { myTableView.reloadData() } break case 2: if(publicList.count == 0) { loadItems() } else { myTableView.reloadData() } break default: break } } internal func tableView(tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { return 0.0 } func loadItems() { switch(mySegmentedControl.selectedSegmentIndex) { case 0: loadItemsNow("privateList") break case 1: loadItemsNow("protectedList") break case 2: loadItemsNow("publicList") break default: break } } func loadItemsNow(listType:String){ myActivityIndicator.startAnimating() let listUrlString = "https://www.swiftdeveloperblog.com/my-list-of-items?listType=" + listType + "&t=" + NSUUID().UUIDString let myUrl = NSURL(string: listUrlString); let request = NSMutableURLRequest(URL:myUrl!); request.HTTPMethod = "GET"; let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in if error != nil { print(error!.localizedDescription) dispatch_async(dispatch_get_main_queue(),{ self.myActivityIndicator.stopAnimating() }) return } do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray if let parseJSON = json { if(listType == "privateList") { self.privateList = parseJSON as! [String] } else if(listType == "protectedList") { self.friendsAndFamily = parseJSON as! [String] } else { self.publicList = parseJSON as! [String] } } } catch { print(error) } dispatch_async(dispatch_get_main_queue(),{ self.myActivityIndicator.stopAnimating() self.myTableView.reloadData() }) } task.resume() } }
Source code of PHP script:
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); if($_GET["listType"] == "privateList") { $private_list = array(); $private_list[] = "Private item 1"; $private_list[] = "Private item 3"; echo json_encode($private_list); return; } if($_GET["listType"] == "protectedList") { $protected_list = array(); $protected_list[] = "Friend item 1"; $protected_list[] = "Friend item 2"; $protected_list[] = "Friend item 3"; $protected_list[] = "Friend item 4"; echo json_encode($protected_list); return; } if($_GET["listType"] == "publicList") { $public_list = array(); $public_list[] = "Public item 1"; $public_list[] = "Public item 2"; $public_list[] = "Public item 3"; $public_list[] = "Public item 4"; $public_list[] = "Public item 5"; echo json_encode($public_list); return; }