首页 > 解决方案 > 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.

标签: iosswiftswiftui

解决方案


好的,这对我有用:

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
    }
}

推荐阅读