ios - SwiftUI:ViewModifier 不监听 onReceive 事件
问题描述
我有一个自定义ViewModifier
,它只是返回带有onReceive
修饰符的相同内容,onReceive
不会触发,这是一个示例代码,您可以复制、粘贴和运行XCode
:
import SwiftUI
import Combine
class MyViewModel: ObservableObject {
@Published var myProperty: Bool = false
}
struct ContentView: View {
@ObservedObject var viewModel: MyViewModel
var body: some View {
Text("Hello, World!")
.modifier(MyOnReceive(viewModel: viewModel))
.onTapGesture {
self.viewModel.myProperty = true
}
}
}
struct MyOnReceive: ViewModifier {
@ObservedObject var viewModel: MyViewModel
func body(content: Content) -> some View {
content
.onReceive(viewModel.$myProperty) { theValue in
print("The Value is \(theValue)") // <--- this is not executed
}
}
}
旨在SwiftUI
禁止onReceive
在 a 内部执行ViewModifier
还是一个错误?我在现实生活中的项目中有一个视图,其中包含一些业务逻辑而变得更大onReceive
,因此我需要通过将其与onReceive
.
解决方案
好的,这对我有用:
func body(content: Content) -> some View {
content
.onAppear() // <--- this makes it work
.onReceive(viewModel.$myProperty) { theValue in
print("-----> The Value is \(theValue)") // <--- this will be executed
}
}
推荐阅读
- java - 当我在 CUCUMBER 中运行 runner 类时,得到“courgette.runtime.CourgetteException: Unable to create the 'target\chrome' directory”
- java - 使用 intellij 中的 gridLayoutmanager 在 1 行上合并 2 列
- python - 如何在 act_window odoo 中添加域
- scala - 函数文字难题上的隐式参数
- redirect - 如何使用参数设置 OpenAPI 重定向响应?
- formatjs - 错误:调试失败。运行 formatjs extract 时输出生成失败
- html - 在html中迭代数组
- mysql - 选择至少一个字段具有另一个表中的值
- apache - Apache .htaccess 重写规则创建无限循环(500 内部服务器错误)
- python - 梯度计算所需的变量之一已通过就地操作进行了修改: