0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Xcode/SwiftUI] 複数のViewを動的に切り替える方法

Posted at

概要

SwiftUIでpickerなどを使い複数のViewを切り替える方法です。

環境

Xcode: 13.4.1
Swift: 5.6.1

実装例

ContentView.swift
import SwiftUI

struct ContentView: View {
    @State private var selection = 0
    
    let titles = [
        "いちご",
        "みかん",
        "ぶどう"
    ]
    
    var body: some View {
        VStack {
            Picker(selection: self.$selection, label: Text("")) {
                ForEach(0 ..< titles.count) {
                    Text(titles[$0])
                }
            }
            .pickerStyle(SegmentedPickerStyle())
            showView()
        }
    }
    
    private func showView() -> AnyView {
        switch selection {
        case 0:
            return AnyView(viewStrawberry())
        
        case 1:
            return AnyView(viewOrange())
        
        case 2:
            return AnyView(viewGrape())
        
        default:
            return AnyView(viewStrawverry())
        }
    }
}

struct viewStrawverry: View {
    var body: some View {
        Text("いちご")
    }
}

struct viewOrange: View {
    var body: some View {
        Text("みかん")
    }
}
struct viewGrape: View {
    var body: some View {
        Text("ぶどう")
    }
}

補足

pickerを用いない場合でも実装は特に変わりません。
viewの切り替えは3個程度の場合はifをVStack内に直接書けますが、切り替えるviewが5個とか多くなってくると
The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expression
というエラー(ifの条件分岐多すぎてコンパイル遅いよ!と怒られる)が出るため、今後要素数が増えることを考慮して初めからswitch文で記述することを推奨します。

0
2
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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?