首页 > 解决方案 > 在预览时增加函数中的变量会产生错误(swiftui)

问题描述

我有这段代码,我在其中调用返回视图的“makeView”函数,在makeView函数中,我递增变量“id”并将其传递给视图,但是当我这样做时,它会显示此错误

“从 SongBook.app (2935) 中的 SongsList_Previews 更新预览耗时超过 5 秒。”

令人惊讶的是,当我注释掉“self.id += 1”行时,一切正常。我是 SwiftUI 的新手,如果我遗漏了一些信息,请原谅我。

struct SongsList: View {
    @State private var id: Int = 0
    var body: some View {
        
        VStack{
            NavigationView {
            List(songs) {
                song in NavigationLink(
                    destination: SongMainView(song: song)) {
                        makeView(song: song)
                    }
            }
        }
    }
        .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .leading)
        .background(Color.orange.opacity(0.2))
        .edgesIgnoringSafeArea(.all)
    }
    
    func makeView(song: Song) -> SongsIndexView {
        self.id += 1;
        return SongsIndexView(song: song, id: self.id)
    }
}

标签: swiftswiftuiswiftui-listswiftui-navigationlinkswiftui-view

解决方案


该变量用@State属性包装器标记。

@State private var id: Int = 0

每次此值更改时,SwiftUI 都会尝试更新视图。

func makeView(song: Song) -> SongsIndexView {
    self.id += 1;
    return SongsIndexView(song: song, id: self.id)
}

这会导致无限循环,例如 -

  1. id = 1, updateView (但现在id = 2因为id += 1
  2. id = 2, updateView (但现在id = 3因为id += 1

在更新视图时,您永远不应该改变状态。


推荐阅读