LoginSignup
5
1

More than 1 year has passed since last update.

【SwiftUI】Navigationlinkで遷移した先で値を更新すると、勝手に画面が戻る件

Posted at

何をするのか?

@ObservedObject監視対象の値を使って描画している画面からNavigationlinkで遷移して、遷移先で監視対象の値を更新すると前画面に勝手に戻ってしまいます。
上記のような事象が発生する理由は監視対象の値を更新すると、前画面が再レンダリングされ、そしてNavigationLinkでDestination指定している画面(遷移先)が破棄されるためだと思われます。
上記の事象に対しての解決策を備忘録として残しておきます。

対応前の処理

対応前は以下のようにForEachでcellModelsの配列の要素を順番に抜き出して、NavigationLinkを並べています。
この処理で画面遷移すると、遷移先で監視対象の値を更新すると、強制的に画面が戻されます。

@ObservedObject var viewModel = ViewModel()

/////////////////////////////////////////////////////////////

ForEach(viewModel.cellModels, id: \.self) { cell in
    NavigationLink(destination: MemoView(folderViewCellModel: cell),
        label: {
             Text(cell.name)
        }
    )
}

対応後の処理

ForEachでindex番号を回して、NavigationLinkやlabelへの値の指定は配列にindexをしてNavigationLinkを並べていきます。
以下の処理だと遷移先で監視対象の値を更新しても、画面が強制的に戻ることはありませんでしが。
原因は正確にはわからないのですが、ForEachで使用している値が監視対象の値だと、変化するたびに再レンダリングされるけど、index番号だったら配列の要素が増えたり減ったりしない限り、値は変わらないので再レンダリングが発生しないのかなと一つ考察を残しておきます。

@ObservedObject var viewModel = ViewModel()

/////////////////////////////////////////////////////////////

ForEach(0..<viewModel.cellModels.count, id: \.self) { index in
    NavigationLink(destination: MemoView(folderViewCellModel: viewModel.cellModels[index]),
        label: {
             Text(viewModel.cellModels[index].name)
        }
    )
}
5
1
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
5
1