观察绑定或状态变量 [英] Observing Binding or State variables

查看:30
本文介绍了观察绑定或状态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在 onReceive 中观察 @State@Binding 值变化的方法.我不能让它工作,我怀疑这是不可能的,但也许有一种方法可以将它们转换为 Publisher 或其他东西,同时保持源更新值,就像它现在所做的那样?

I'm looking for a way of observing @State or @Binding value changes in onReceive. I can't make it work, and I suspect it's not possible, but maybe there's a way of transforming them to Publisher or something while at the same time keeping the source updating value as it's doing right now?

你可以在下面找到我为什么需要这个的一些背景:

Below you can find some context why I need this:

我有一个父视图,它应该基于这个库显示半模态:https://github.com/AndreaMiotto/PartialSheet

I have a parent view which is supposed to display half modal based on this library: https://github.com/AndreaMiotto/PartialSheet

为此,我创建了一个 @State private var modalPresented: Bool = false 并且我用它来显示和隐藏这个模态视图.这工作正常,但我的父母在初始化 self 后立即初始化这个模态,所以我完全失去了 onAppearonDisappear 修饰符.问题是我需要 onAppear 每次呈现此模态时执行一些数据获取(理想情况下,当模态被解除时,我也会取消网络任务).

For this purpose, I've created a @State private var modalPresented: Bool = false and I'm using it to show and hide this modal view. This works fine, but my parent initializes this modal immediately after initializing self, so I completely loose the onAppear and onDisappear modifiers. The problem is that I need onAppear to perform some data fetching every time this modal is being presented (ideally I'd also cancel network task when modal is being dismissed).

推荐答案

改用 ObservableObject/ObservedObject.

use ObservableObject / ObservedObject instead.

一个例子

import SwiftUI

class Model: ObservableObject {
    @Published var txt = ""
    @Published var editing = false
}

struct ContentView: View {

    @ObservedObject var model = Model()

    var body: some View {
        TextField("Email", text: self.$model.txt, onEditingChanged: { edit in
            self.model.editing = edit
        }).onReceive(model.$txt) { (output) in
            print("txt:", output)
        }.onReceive(model.$editing) { (output) in
            print("editing:", output)
        }.padding().border(Color.red)
    }
}

这篇关于观察绑定或状态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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