LoginSignup
1
3

More than 3 years have passed since last update.

[SwiftUI]sheetでViewを出し分ける

Posted at

SwiftUIでsheetを使ってViewを出し分けを実装した時につまづいたのでメモ。

できなかったこと

  • View.sheetを2回書く
  • sheetの中でif elseで出し分け

実現できた実装方法

こちらを使用しました。

public func sheet<Item, Content>(item: Binding<Item?>, onDismiss: (() -> Void)? = nil, @ViewBuilder content: @escaping (Item) -> Content) -> some View where Item : Identifiable, Content : View

ItemがIdentifiableに準拠している時に、それに対するViewを返します。

具体的な実装方法は、こちらです。

Routerクラス

import SwiftUI

extension Identifiable where Self: Hashable {
    typealias ID = Self
    var id: Self { self }
}

enum ContentRouter: View, Hashable, Identifiable {

    case first
    case second(text: String)

    var body: some View {
        switch self {
        case .first: return AnyView(FirstView())
        case .second: return AnyView(SecondView(text: "Second"))
        }
    }

}

View

struct ContentView: View {

    @State var router: ContentRouter?

    var body: some View {
        VStack {
            Button.init("First") {
                self.router = .first
            }
            Button.init("Second") {
                self.router = .second(text: "Second")
            }
        }.sheet(item: self.$router) { $0 }

    }
}

結果

それぞれのボタンで、別々のViewを出すことができました。
.secondの場合の値の受け渡しもできました。

ソースはこちらにあります。
https://github.com/usk-sample/swiftui-router-sample/tree/main/SwiftUIRouterSample

参考

https://developer.apple.com/documentation/swiftui/view/sheet(item:ondismiss:content:)
https://qiita.com/1amageek/items/e90e1cfb0ad497e8b27a
https://yanamura.hatenablog.com/entry/2019/09/05/150849

1
3
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
1
3