[iOSアプリ開発][Xcode 8] Segmented Control を実装する

切り替えボタンである Segmented Control を使い、押したボタンに応じてラベルを切り替えるような機能を実装する方法。

具体的には Segmented Control に 1 2 3 … 10 とボタンを用意し、3を押したらラベルが3に、7を押したらラベルが7になるようにしたい。

(1)プロジェクトを作成する。

(2)Project navigator で main.storyboard を選ぶ。Object library から Segmented Control を配置したい画面にドラッグアンドドロップする。

(3)2の Segmented Control が選択された状態で、Attributes inspector > Segments を 10 にする。ボタンの数が 10 になった。

(4)同じくAttributes inspector の Segment をそれぞれ選択し、Title にボタンに表示したいテキストを入力する(Segmentは1ではなく、0 から始まる)。

(5)Object library から Label を、配置したい画面にドラッグアンドドロップする。

(6)右上の円が二つ重なった Show the Assistant editor アイコンをクリック。

(7)2の Segment Control を右側のエディタに右クリックでドラッグアンドドロップ。以下のように設定、Connect をクリック。

Connection:Outlet
Name:SegmentedControl
Type:UILabel
Storage:Weak

(8)5の Label を右側のエディタに右クリックでドラッグアンドドロップ。以下のように設定、Connect をクリック。

Connection:Outlet
Name:Label
Type:UILabel
Storage:Weak

(9)2の Segment Control を再び右側のエディタに右クリックでドラッグアンドドロップ。以下のように設定、Connect をクリック。

Connection:Action
Name:ChangeLabel
Type:AnyObject
Event:Value Changed
Arguments:Sender

(10)右上の Show the Standard editor アイコンをクリック、Project navigator で ViewController.swift をクリック。エディタだけが表示される。

(11)9に以下のコードを書く。

@IBAction func ChangeLabel1(_ sender: AnyObject) {
    if sender.selectedSegmentIndex == 0 {
  Label.text = "1"
 }
    if sender.selectedSegmentIndex == 1 {
  Label.text = "2"
 }
    if sender.selectedSegmentIndex == 2 {
  Label.text = "3"
 }
    if sender.selectedSegmentIndex == 3 {
  Label.text = "4"
 }
    if sender.selectedSegmentIndex == 4 {
  Label.text = "5"
 }
    if sender.selectedSegmentIndex == 5 {
  Label.text = "6"
 }
    if sender.selectedSegmentIndex == 6 {
  Label.text = "7"
 }
    if sender.selectedSegmentIndex == 7 {
  Label.text = "8"
 }
    if sender.selectedSegmentIndex == 8 {
  Label.text = "9"
 }
    if sender.selectedSegmentIndex == 9 {
  Label.text = "10"
 }
}

これで完成!

なお、Segmented Control を選択した上で、Attributes inspector の Segmented Control > State > Momentary にチェックを入れると、Segmented Control で押したボタンがハイライトされたままにならない。

参考:
How to Add a Segmented Controller with Swift in Xcode – YouTube
https://www.youtube.com/watch?v=FClWQCeWU-8

【Swift】Segmented Controlの使い方。選択肢の中からどれか1つを選択するボタン。 | はじはじアプリ体験記
http://hajihaji-lemon.com/smartphone/swift/segmented-control/