Skip to content

Instantly share code, notes, and snippets.

@hukusuke1007
Last active April 15, 2021 07:41
Show Gist options
  • Select an option

  • Save hukusuke1007/333fe0ec5ee73e79f09a9b5be8ea4d72 to your computer and use it in GitHub Desktop.

Select an option

Save hukusuke1007/333fe0ec5ee73e79f09a9b5be8ea4d72 to your computer and use it in GitHub Desktop.
SwiftUIのモーダル遷移とプッシュ遷移のサンプルコード
import SwiftUI
extension Identifiable where Self: Hashable {
typealias ID = Self
var id: Self { self }
}
struct SecondView: View {
let text: String
init(text: String) {
self.text = text
print("SecondView init")
}
var body: some View {
VStack {
Text(text)
}
.onAppear {
print("SecondView onAppear")
}
.onDisappear {
print("SecondView Disappear")
}
}
}
struct ThirdView: View {
var body: some View {
Text("ThirdView")
}
}
struct SampleModalPushView: View {
enum Presentation: View, Hashable, Identifiable {
case second(text: String)
case third
var body: some View {
switch self {
case .second(let text): return AnyView(SecondView(text: text))
case .third: return AnyView(ThirdView())
}
}
}
@State var presentation: Presentation?
@State var presentationNav: (Bool, Presentation?) = (false, nil)
var body: some View {
NavigationView {
ZStack {
VStack(spacing: 20) {
Button(action: {
presentation = .second(text: "aaa")
}) {
Text("モーダル遷移")
}
Button(action: {
presentationNav = (true, .second(text: "test"))
}) {
Text("プッシュ遷移")
}
}
NavigationLink(
destination: presentationNav.1,
isActive: $presentationNav.0,
label: EmptyView.init
)
}
}
.sheet(item: $presentation) { $0.body }
}
}
struct SampleModalPushView_Previews: PreviewProvider {
static var previews: some View {
SampleModalPushView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment