【问题标题】:How do you call a content view function from an instantiated class in Swift?如何从 Swift 中的实例化类中调用内容视图函数?
【发布时间】:2020-05-31 23:51:40
【问题描述】:

在我的 ContentView 中,我实例化了一个名为 timer 的类。当计时器的“timerText”达到“0:00”时,我希望计时器调用 ContentView 中的函数来编辑视图,其中包含计时器无法访问的信息。但是,我不知道如何从这个计时器类内部调用 ContentView 中的函数。这甚至可能吗?

如果这不可能,我可以通过在 ContentView 中创建一个始终与计时器对象的“timerText”变量同步的“timerText”变量来实现相同的目标。这样,当 ContentView 的“timerText”为“0:00”时,我可以像往常一样调用该函数,因为我已经在 ContentView“内部”了。但是,我不知道如何在两个不同的类中同步一个变量。有没有办法做到这一点?

【问题讨论】:

    标签: swift function class swiftui


    【解决方案1】:

    如果我正确理解您想要实现的目标,此解决方案将帮助您:

    1. 使用Combine 并让您的timerText @Published;
    2. ContentView 中,在任何View 处使用.onReceive func,并在需要时调用您的函数。

    下面是简单的代码示例:

    import SwiftUI
    import Combine
    
    final class SpecialTimer: ObservableObject {
    
        @Published var timerText = "0:01"
    
        func resetTimer() {
            timerText = "0:00"
        }
    
    }
    
    struct SpecialTimerView: View {
    
        @EnvironmentObject var timer: SpecialTimer
        @State private var didEditedSpecialInfo = false
    
        var body: some View {
    
            VStack {
    
                Text(timer.timerText)
                    .onReceive(timer.$timerText) { timerText in
                        guard timerText == "0:00" else { return }
                        self.whenTimerResets()
                }
    
                Button(action: {self.timer.resetTimer()} ) {
                    Text("reset timer!")
                }
    
                Text("timer did reset")
                    .opacity(didEditedSpecialInfo ? 1 : 0)
    
            }
    
        }
    
        private func whenTimerResets() {
            print("edit the view with information that is not accessible from the timer")
            didEditedSpecialInfo = true
    
        }
    
    }
    
    struct SpecialTimerView_Previews: PreviewProvider {
        static var previews: some View {
            SpecialTimerView()
                .environmentObject(SpecialTimer())
        }
    }
    
    

    【讨论】:

    • 这正是我所需要的,它就像一个魅力 Text(timer.timerText) .onReceive(timer.$timerText) { timerText in guard timerText == "0:00" else { return }
    猜你喜欢
    • 2012-06-04
    • 2018-03-28
    • 1970-01-01
    • 2019-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多