gpt4 book ai didi

swift - 如何删除 SwiftUI 中标有@ObjectBinding 的对象?

转载 作者:行者123 更新时间:2023-11-28 05:40:17 24 4
gpt4 key购买 nike

我想删除一个标记为 @ObjectBinding 的对象,例如为了清理一些 TextFields

我试图将对象引用设置为 nil,但没有成功。

import SwiftUI
import Combine

class A: BindableObject {
var didChange = PassthroughSubject<Void, Never>()

var text = "" { didSet { didChange.send() } }
}

class B {
var property = "asdf"
}

struct DetailView : View {
@ObjectBinding var myObject: A = A() //@ObjectBinding var myObject: A? = A() -> Gives an error.
@State var mySecondObject: B? = B()

var body: some View {

VStack {
TextField($myObject.text, placeholder: Text("Enter some text"))
Button(action: {
self.test()
}) {
Text("Clean up")
}
}
}

func test() {
//myObject = nil
mySecondObject = nil
}
}

如果我尝试使用可选的 @ObjectBinding,我会收到错误

"Cannot convert the value of type 'ObjectBinding' to specified type 'A?'".

它只适用于 @State

问候

最佳答案

你可以这样做:

class A: BindableObject {
var didChange = PassthroughSubject<Void, Never>()

var form = FormData() { didSet { didChange.send() } }

struct FormData {
var firstname = ""
var lastname = ""
}

func cleanup() {
form = FormData()
}
}

struct DetailView : View {
@ObjectBinding var myObject: A = A()

var body: some View {

VStack {
TextField($myObject.form.firstname, placeholder: Text("Enter firstname"))
TextField($myObject.form.lastname, placeholder: Text("Enter lastname"))
Button(action: {
self.myObject.cleanup()
}) {
Text("Clean up")
}
}
}
}

关于swift - 如何删除 SwiftUI 中标有@ObjectBinding 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57004311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com