LoginSignup
17
27

More than 5 years have passed since last update.

[Swift3]SegmentedControlでViewを切り替える

Posted at

やりたいこと

SegmentedControlで複数のViewを切り替えたい場面はよくあると思うので、忘備録として書き残しておきます。

画面の用意

最初に、以下のようにStoryBoardでNavigationControllerを追加します。
NavigationControllerを追加したらViewControllerにSegmentedControlを設置しましょう。
また、今回切り替える子ViewControllerはコード上で作成することにします。

スクリーンショット 2017-01-23 0.14.43.png

SegmentedControlの準備

SegmentedControlのSegueをViewControllerに作成しましょう。IBActionを作成するときはTypeをAnyではなくUISegmentedControlに設定することでダウンキャストせずに受け取ることができます。

スクリーンショット 2017-01-23 0.23.44.png

ViewController

ソースは以下になります。今回の例ではMapViewController,ListViewControllerという2つのVCを作成し、setupでそれらのviewを追加しています。

SegmentedControlがタップされると、引数であるsenderからselectedSegmentIndexでタップした項目を取得することができます。Indexは左から順に振られています。

switch文で項目に応じたviewを最前面に移動させて画面切り替えを行っています。

ViewController.swift
import UIKit

class ViewController: UIViewController {

    var MapVC:MapViewController = MapViewController()
    var ListVC:ListViewController = ListViewController()

    @IBOutlet weak var segmentButton: UISegmentedControl!


    override func viewDidLoad() {
        super.viewDidLoad()

        setup()

    }


    func setup(){
        segmentButton.setTitle("Map", forSegmentAt: 0)
        segmentButton.setTitle("List", forSegmentAt: 1)

        MapVC.view.backgroundColor = UIColor.cyan
        ListVC.view.backgroundColor = UIColor.magenta

        self.view.addSubview(ListVC.view)
        self.view.addSubview(MapVC.view)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func segmentButton(_ sender: UISegmentedControl) {

        switch sender.selectedSegmentIndex {
        case 0:
            self.view.bringSubview(toFront: MapVC.view)
        case 1:
            self.view.bringSubview(toFront: ListVC.view)
        default:
            print("")
        }
    }
}

実行すると以下のようにシアンの画面が表示され、SegmentedControlをタップするとマゼンタの画面を表示することができます。

スクリーンショット 2017-01-23 21.18.40.png スクリーンショット 2017-01-23 21.19.05.png

17
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
27