[SwiftUI]遷移先から戻った時の制御

12063 ワード

遷移先ごとに戻った時の制御を行う

  • 遷移元であるContentViewonAppearを呼ぶことで、遷移先から戻った時の検知はできる
  • 下記のように遷移先がDetailViewOtherViewと複数ある場合、それぞれから戻った処理を個別に制御したい場合どうするか
struct ContentView: View {
  enum views: String, CaseIterable {
    case detail
    case other
  }

  var body: some View {
    NavigationView {
      List {
        ForEach(views.allCases, id: \.self) { view in
          switch view {
          case .detail:
            NavigationLink("DetailView", destination: DetailView())
          case .other:
            NavigationLink("OtherView", destination: OtherView())
          }
        }
      }
    }
  }
}
  • その場合は、destinationで指定しているViewに対してonDisappearを呼び出す
struct ContentView: View {
  enum views: String, CaseIterable {
    case detail
    case other
  }

  var body: some View {
    NavigationView {
      List {
        ForEach(views.allCases, id: \.self) { view in
          switch view {
          case .detail:
            NavigationLink("DetailView", destination: DetailView().onDisappear {
              print("back to DetailView")
            })
          case .other:
            NavigationLink("OtherView", destination: OtherView().onDisappear {
              print("back to OtherView")
            })
          }
        }
      }
    }
  }
}

onAppearとの呼び出し順

  • ちなみに、遷移元のonAppearと、destination内のonDisappearとでは、onAppearのほうが先に呼ばれる様子
struct ContentView: View {
  enum views: String, CaseIterable {
    case detail
    case other
  }

  var body: some View {
    NavigationView {
      List {
        ForEach(views.allCases, id: \.self) { view in
          switch view {
          case .detail:
            NavigationLink("DetailView", destination: DetailView().onDisappear {
              print("back to DetailView")
            })
          case .other:
            NavigationLink("OtherView", destination: OtherView().onDisappear {
              print("back to OtherView")
            })
          }
        }
      }
    }
    .onAppear {
      print("back to Any")
    }
  }
}
  • 出力ログ
back to Any
back to DetailView
back to Any
back to OtherView
back to Any
back to OtherView
back to Any
back to DetailView