Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Segmented control - Switch multiple views

Tags:

ios

swift

xcode6

Until now I still can't figure how to switch multiple views in one view controller. My storyboard is like this one.

enter image description here

Right now I want to embed two views inside my view controller.

enter image description here

My code for segmented control to switch two views in one view controller so far.

import UIKit  class PopularHistoryViewController: UIViewController {      @IBOutlet weak var segmentedControl: UISegmentedControl!      @IBAction func indexChanged(sender: UISegmentedControl) {         switch segmentedControl.selectedSegmentIndex         {         case 0:             NSLog("Popular selected")             //show popular view         case 1:             NSLog("History selected")             //show history view         default:             break;          }     }      override func viewDidLoad() {         super.viewDidLoad()          // Do any additional setup after loading the view.     }   } 

Another thing, If I put two views inside my controller, what is best practice to differentiate it?

like image 256
Nurdin Avatar asked Jan 15 '15 03:01

Nurdin


2 Answers

If you want to do UI layout in Xcode for the two overlapping subviews, a better solution is to use two UIContainerViewController, and use the same way of setting the hidden property as suggested in the above answer.

enter image description here

like image 154
Xiaojun Avatar answered Sep 21 '22 13:09

Xiaojun


You can use the isHidden property of the UIView to show/hide your required views. First you have to link both views to IBOutlets through the Interface builder

@IBOutlet weak var historyView: UIView! @IBOutlet weak var popularView: UIView!  @IBAction func indexChanged(_ sender: UISegmentedControl) {     switch segmentedControl.selectedSegmentIndex {     case 0:         historyView.isHidden = true         popularView.isHidden = false     case 1:         historyView.isHidden = false         popularView.isHidden = true     default:         break;     } } 

Note: it was named hidden in Swift 1 and 2.

like image 23
rakeshbs Avatar answered Sep 21 '22 13:09

rakeshbs