3
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 3 years have passed since last update.

[SwiftUI] Viewを強制再読み込みする賢くない方法

Posted at

どうしてもViewを再読み込みしたいが、どうやってもうまくいかない、という場合、賢くないですがこの方法でいけます。
SwiftUIのお気持ちに沿って作っていればそもそも強制再読み込みは必要ないはずなので、対処法として正しいのは設計の見直しです。

対処

struct HogeView: View {
    var body: some View {
        Hoge()
    }
}

を強制再読み込みしたい場合、

struct HogeView: View {
    @State private var flag = true

    func refresh(){
        flag.toggle()
    }

    var mainView: some View {
        Hoge()
    }

    var body: some View {
        Group{
            if flag{
                mainView
            }else{
                mainView
            }
        }
    }
}

としてあげれば、flagを切り替えるたびにmainViewが計算しなおされるので実質再読み込みになります。

自戒

本当に賢くないのでSwiftUIをちゃんと勉強します。

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