我想删除标记为@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
使用可选内容,则会收到错误消息
“无法将类型'ObjectBinding'的值转换为指定的类型 “ A?”。
它仅适用于@State
。
致谢
答案 0 :(得分:1)
您可以执行以下操作:
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")
}
}
}
}
答案 1 :(得分:0)