【问题标题】:Use .onReceive code in multiple instances - SwiftUI在多个实例中使用 .onReceive 代码 - SwiftUI
【发布时间】:2020-06-22 23:41:56
【问题描述】:

我有这个代码:

VStack {
            if viewRouter.currentPage == "onboardingView" {
                OnboardingView()
            } else if viewRouter.currentPage == "homeView" {
                TabView {
                    HomeView(mealsController: self.mealsController)
                        .tabItem {
                            Image(systemName: "house")
                            Text("Menu")
                    }
                    SettingsView(mealsController: self.mealsController)
                        .tabItem {
                            Image(systemName: "slider.horizontal.3")
                            Text("Settings")
                    }
                }
                .accentColor(Color(getThemeConstants.accentThemeColor))
            }
        }

在我的底部:

.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
...
}
.onAppear() {
...
}

.onReceive内部我有一堆代码需要在.onAppear上重用,我该如何重用这种代码?

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    只需在一些私有函数中提取公共代码并从两个修饰符中调用它,如下所示

    .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
       self.handlerFunction()
    }
    .onAppear() {
       self.handlerFunction()
    }
    
    ...
    
    private func handlerFunction() {
       // move common code here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多