How do I use a UISegmentedControl to switch views?
The simplest approach is to have two views that you can toggle their visibility to indicate which view has been selected. Here is some sample code on how it can be done, definitely not an optimized way to handle the views but just to demonstrate how you can use the UISegmentControl to toggle the visible view:
- (IBAction)segmentSwitch:(id)sender {
UISegmentedControl *segmentedControl = (UISegmentedControl *) sender;
NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;
if (selectedSegment == 0) {
//toggle the correct view to be visible
[firstView setHidden:NO];
[secondView setHidden:YES];
}
else{
//toggle the correct view to be visible
[firstView setHidden:YES];
[secondView setHidden:NO];
}
}
You can of course further re-factor the code to hide/show the right view.
Change views using Segmented Control
Here i have created a complete solution as per your requirement.
Swift 4
//
// SegementedVC.swift
//
// Created by Test User on 01/02/18.
// Copyright © 2018 Test User. All rights reserved.
//
import UIKit
class SegementedVC: UIViewController {
//----------------------------------------------------------------
// MARK:-
// MARK:- Outlets
//----------------------------------------------------------------
@IBOutlet weak var segmentControl : UISegmentedControl!
@IBOutlet weak var containerView : UIView!
//----------------------------------------------------------------
// MARK:-
// MARK:- Variables
//----------------------------------------------------------------
private lazy var firstViewController: FirstViewController = {
// Load Storyboard
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
// Instantiate View Controller
var viewController = storyboard.instantiateViewController(withIdentifier: "FirstViewController") as! FirstViewController
// Add View Controller as Child View Controller
self.add(asChildViewController: viewController)
return viewController
}()
private lazy var secondViewController: SecondViewController = {
// Load Storyboard
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
// Instantiate View Controller
var viewController = storyboard.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
// Add View Controller as Child View Controller
self.add(asChildViewController: viewController)
return viewController
}()
//----------------------------------------------------------------
// MARK:-
// MARK:- Abstract Method
//----------------------------------------------------------------
static func viewController() -> SegementedVC {
return UIStoryboard.init(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SegementedView") as! SegementedVC
}
//----------------------------------------------------------------
// MARK:-
// MARK:- Memory Management Methods
//----------------------------------------------------------------
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//----------------------------------------------------------------
// MARK:-
// MARK:- Action Methods
//----------------------------------------------------------------
@IBAction func segmentValueChanged(_ sender: UISegmentedControl) {
updateView()
}
//----------------------------------------------------------------
// MARK:-
// MARK:- Custom Methods
//----------------------------------------------------------------
private func add(asChildViewController viewController: UIViewController) {
// Add Child View Controller
addChildViewController(viewController)
// Add Child View as Subview
containerView.addSubview(viewController.view)
// Configure Child View
viewController.view.frame = containerView.bounds
viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Notify Child View Controller
viewController.didMove(toParentViewController: self)
}
//----------------------------------------------------------------
private func remove(asChildViewController viewController: UIViewController) {
// Notify Child View Controller
viewController.willMove(toParentViewController: nil)
// Remove Child View From Superview
viewController.view.removeFromSuperview()
// Notify Child View Controller
viewController.removeFromParentViewController()
}
//----------------------------------------------------------------
private func updateView() {
if segmentControl.selectedSegmentIndex == 0 {
remove(asChildViewController: secondViewController)
add(asChildViewController: firstViewController)
} else {
remove(asChildViewController: firstViewController)
add(asChildViewController: secondViewController)
}
}
//----------------------------------------------------------------
func setupView() {
updateView()
}
//----------------------------------------------------------------
// MARK:-
// MARK:- View Life Cycle Methods
//----------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
self.setupView()
}
//----------------------------------------------------------------
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
//----------------------------------------------------------------
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
}
Storyboard Screenshots
Swift - Segmented control - Switch multiple views
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.
switching views between views in ios using segmented control
Depending on how demanding the content four views is, I would suggest to make one main view for the segmented control and set up four container views in the main view. The three of them should be hidden and then you can toggle between the four views (show/hide).
This is only a good solution if the views' codes are very "soft" or it'll be very slow to run 4-5 views at the same time. If it's four hardcore views I would prefer to use the standard navigation tab bar control instead..
//////// EXAMPLE ////////
The setup will be with one UIViewController for the background. On this view we will place one UISegmentedControl + four container views. The four container views should be placed on the top of each other. The three of the container views are hidden so you only see one.
BackgroundViewController.h:
#import <UIKit/UIKit.h>
@interface BackgroundViewController : UIViewController {
IBOutlet UISegmentedControl *segmentedControl;
UIView actualView;
}
@property (nonatomic, weak) IBOutlet UIView *containerOne;
@property (nonatomic, weak) IBOutlet UIView *containerTwo;
@property (nonatomic, weak) IBOutlet UIView *containerThree;
@property (nonatomic, weak) IBOutlet UIView *containerFour;
@end
Here's an example of the IBAction for the segmented control.
- (void) viewDidLoad {
actualView = self.containerOne;
UIView *fromView = nil;
UIView *toView = nil;
self.containerOne.hidden = NO;
self.containerTwo.hidden = YES;
self.containerThree.hidden = YES;
self.containerFour.hidden = YES;
}
- (IBAction)segmentSwitchClick {
NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;
UIView *fromView = actualView;
UIView *toView = nil;
switch (selectedSegment) {
case 0: {
toView = [self containerOne];
break;
}
case 1: {
toView = [self containerTwo];
break;
}
case 2: {
toView = [self containerThree];
break;
}
case 3: {
toView = [self containerFour];
break;
}
default:
break;
}
}
[UIView transitionFromView:fromView toView:toView duration:1.9 options:UIViewAnimationOptionShowHideTransitionViews | UIViewAnimationOptionCurveLinear
completion:^(BOOL finished) {
if (finished) {
actualView = toView;
}
}];
}
PS I haven't tried it, but it should work.
Switching Between Views with a UISegmentedControl
I have answered a similar (not the same, but similar result) question here: How To Switch Views With NSNotifications
Basically you can switch views using NSNotifications. Your fist view will load and using NSNotifications you can send a notification to a custom class that listens and responds by changing the view; when you select an index on the UISegmentControl, your views would change.
It would look like this in your code, in your NSObject Class ButtonHandler
:
- (IBAction)segmentChanged:(id)sender{
UISegmentedControl *segmentedControl = sender;
switch (segmentedControl.selectedSegmentIndex) {
case 0:
[[NSNotificationCenter defaultCenter] postNotificationName:@"notifyButtonPressed1" object:self];
break;
case 1:
[[NSNotificationCenter defaultCenter] postNotificationName:@"notifyButtonPressed2" object:self];
break;
case 2:
[[NSNotificationCenter defaultCenter] postNotificationName:@"notifyButtonPressed3" object:self];
break;
default:
break;
}
}
Then simply follow the rest of the code I have set out in the other post.
This is the effect:
UPDATE
I have created a tutorial on how to do this at this link: iOS Custom Navigation with UISegmentedControl
To set the view to be the same as the device bound use the following:
//this will get the size of your device view
//and set it to width and height aka w & h
int w = self.view.frame.size.width;
int h = self.view.frame.size.height;
//THIS SETS THE SIZE AND POSITION OF THE NEW CONTENT
self.content.view.frame = CGRectMake(0, 0, w, h);
Segmented control to switch collection views
You create a different instance each line
addChild(FirstCVC())
addChild(SecondCVC())
addChild(ThirdCVC())
addChild(FourthCVC())
self.view.addSubview(FirstCVC().view)
self.view.addSubview(SecondCVC().view)
self.view.addSubview(ThirdCVC().view)
self.view.addSubview(FourthCVC().view)
FirstCVC().didMove(toParent: self)
SecondCVC().didMove(toParent: self)
ThirdCVC().didMove(toParent: self)
FourthCVC().didMove(toParent: self)
FirstCVC().view.frame = self.view.bounds
SecondCVC().view.frame = self.view.bounds
ThirdCVC().view.frame = self.view.bounds
FourthCVC().view.frame = self.view.bounds
while it should be
let vc1 = FirstCVC()
let vc2 = SecondCVC()
let vc3 = ThirdCVC()
let vc4 = FourthCVC()
addChild(vc1)
addChild(vc2)
addChild(vc3)
addChild(vc4)
self.view.addSubview(vc1.view)
self.view.addSubview(vc2.view)
self.view.addSubview(vc3.view)
self.view.addSubview(vc4.view)
vc1.didMove(toParent: self)
vc2.didMove(toParent: self)
vc3.didMove(toParent: self)
vc4.didMove(toParent: self)
vc1.view.frame = self.view.bounds
vc2.view.frame = self.view.bounds
vc3.view.frame = self.view.bounds
vc4.view.frame = self.view.bounds
Tip : Also you better create an extension instead of repeating the 4 lines for each vc
Switch the sub viewController use segmented control
Follow below steps.
Add VC1 & VC2 as a childVC of mainVC.
On segment 1 selection
VC1.view.hidden = false
&vc2.view.hidden = true
On segment 2 selection
VC2.view.hidden = false
&vc1.view.hidden = true
take reference
How-to-add-childVC
How-tobind-segment-control-action
Code work
@IBAction func indexChanged(_ sender: AnyObject) {
switch segmentedControl.selectedSegmentIndex
{
case 0:
vc1.view.hidden = false
vc2.view.hidden = true
case 1:
vc2.view.hidden = false
vc1.view.hidden = true
default:
break
}
}
UISegmentedControl and View switching problem
The issue is your BlueView
and PurpleView
are sub views of the GreenView
. Since they are subViews, when you hide the GreenView
, they also get hidden. So make all three views siblings (in the same level)
Now your view hierarchy is below
- View
- GreenView
- BlueView
- PurpleView
Change it to
- View
- GreenView
- BlueView
- PurpleView
Related Topics
Swift 3 Core Data Delete Object
Converting Between Nsdata and Base64 Strings
How to Use a Uisegmentedcontrol to Switch Views
How to Access Coredata Model in Today Extension (Ios)
Change Default Icon for Moving Cells in Uitableview
Swift - How to Remove a Decimal from a Float If the Decimal Is Equal to 0
Get MAC Address of Bluetooth Low Energy Peripheral in iOS
Open a View Controller When a iOS Push Notification Is Received
How to Underline a Uilabel in Swift
Uisearchbar Presented by Uisearchcontroller in Table Header View Animates Too Far When Active
Uialertview/Uialertcontroller iOS 7 and iOS 8 Compatibility
Wkwebview Persistent Storage of Cookies
Change Text of "Return" Keyboard Button
iOS - Mkmapview Place Annotation by Using Address Instead of Lat/Long
How to Detect Delete Key on an Uitextfield in iOS 8
-[Uiapplication Delegate] Must Be Called from Main Thread Only