4

I need to change views using a Segmented Control. In the following example I have put two view containers in the same location:

enter image description here

The second container is hidden and I will show it through code every time I use the segmented control. (Although it does not show it either.)

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var container1: UIView!
    @IBOutlet weak var container2: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func showComponent(_ sender: Any) {
        if (sender as AnyObject).selectedSegmentIndex == 0 {
            UIView.animate(withDuration: 0.5, animations: {
                self.container1.alpha = 1
                self.container2.alpha = 0
            })
        } else {
            UIView.animate(withDuration: 0.5, animations: {
                self.container1.alpha = 0
                self.container2.alpha = 1
            })
        }
    }

}

Do you know of any other way to do it?

Is there any way to customize the SegmentedControl as if it were a TAB?

2
  • You just want to hide and show container. Commented Feb 1, 2018 at 12:34
  • just use a single containerView and depending on the segmentControl index just add the childViewController or remove the childViewController Commented Feb 1, 2018 at 13:46

2 Answers 2

29

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

enter image description here

enter image description here

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

Do you think you can send the code to my email? [email protected]
Sure, You can download whole working demo using this link: dropbox.com/s/cd2c7tmseoh9lp4/…
This works perfect. The only problem I have is if I add constraints to segment control to occupy whole width, the control gets hidden. Any ideas?
1
  1. Would be great if you can send me a project. But maybe it's not needed if you can try to follow next steps.

  2. I would do it a different way. In your VC add the UIView. Call it container view. Then create 2 separate views in xib (nib) more here and here. and then add these 2 views into container view: view.addSubsire(view1) and view.addSubsire(view2)

  3. Then as you did just check the segmented control and show the view you need.

  4. Don't forget about UI Debugging. Use this amazing feature: link

It might take some time to implement but these are the basics that you need to know in any case so it definitely would be useful.

Hope it helps! Good luck!

PS. The answer posted above - not sure if it helps since you need the tabs to be half page?

3 Comments

It's a solution I had thought about, but I want to avoid creating .xip files
got it! if it's easy to explain, could you please share why you try to avoid it?
for example i like using it since it's reusable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.