SwiftUI视图因Timer对象而冻结

rpppsulh  于 2023-06-04  发布在  Swift
关注(0)|答案(1)|浏览(130)

当我尝试使用Timer和.onReceive(timer)修饰符更新SwiftUI视图中的文本时,视图冻结。

import SwiftUI
import Combine
import AVFoundation

var globalText: String = "abc"

struct ContentView : View {

    @State private var myText = globalText
    
    let timer = Timer.publish(every: 1, on: .current, in: .default)
                     .autoconnect()

    var body: some View {
        ZStack {
            AVContainer().ignoresSafeArea()
            Text(myText)
                .onReceive(timer) { _ in myText = globalText }
                .font(.largeTitle)
        }
    }
}

struct AVContainer : UIViewRepresentable { ... }

我做错了什么?

blmhpbnm

blmhpbnm1#

最近我的AR应用也遇到了类似的问题。在本例中,您需要在ContentView结构中声明并示例化视图,然后在AVContainer结构中创建其绑定变量。我不能解释为什么下面的方法有效,但它肯定有效-不再有冻结。

import SwiftUI
import Combine
import AVFoundation

var globalText: String = "abc"

struct ContentView : View {    
    @State var yourView = YourView(frame: .zero)
    @State var myText = globalText
    
    let timer = Timer.publish(every: 1, on: .current, in: .default)
                     .autoconnect()

    var body: some View {
        ZStack {
            AVContainer(yourView: $yourView).ignoresSafeArea()
            Text(myText)
                .onReceive(timer) { _ in myText = globalText }
                .font(.largeTitle)
            VStack {
                Spacer()
                Button("Restart App") {
                    self.timer.upstream.connect().cancel()
                    myText = "..."
                }
            }
        }
    }
}    
struct AVContainer : UIViewRepresentable { 
    @Binding var yourView: YourView
    // code here ...
}

相关问题