SwiftUI:ViewModifier不侦听onReceive事件 [英] SwiftUI: ViewModifier doesn't listen to onReceive events

查看:55
本文介绍了SwiftUI:ViewModifier不侦听onReceive事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的 ViewModifier ,它仅返回与 onReceive 修饰符关联的相同内容,不会触发 onReceive ,这是一个您可以复制,粘贴并在 XCode 中运行的示例代码:

I have a custom ViewModifier which simply returns the same content attached with a onReceive modifier, the onReceive is not triggered, here is a sample code that you can copy, paste and run in 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 ViewModifier 内部执行还是错误?我在现实生活中的项目中有了一个视图,该视图变得更大了,并且在 onReceive 中放入了一些业务逻辑,因此我需要通过将视图与 onReceive 分开来清理该视图.

is SwiftUI designed to disallow onReceive to execute inside a ViewModifier or is it a bug ? I have a view in my real life project that gets bigger with some business logic put inside onReceive, so I need to clean that view by separating it from 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
    }
}

这篇关于SwiftUI:ViewModifier不侦听onReceive事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆