gpt4 book ai didi

ios - 从初始化器返回而不初始化所有存储的属性 - SwiftUI 绑定(bind)错误

转载 作者:行者123 更新时间:2023-12-05 08:49:10 25 4
gpt4 key购买 nike

我有几个级联模式需要根据某些后台进程进行刷新。为了实现这一点,我创建了一个结构,我在其中保存了 UI 的所有逻辑,并使用 UIHostingController.init(rootView: views) 调用了几个 SwiftUI View 。

当我想通过单击 subview 中的按钮关闭 View 时,挑战就来了。我正在尝试使用 @State 和 @Binding,但绑定(bind)迫使我在 subview 中初始化变量。

这是 child 的代码:

struct ResultViewSilence: View {

@Binding var isDismissView: Bool
var hasSilence: Bool
let photolibrary = PhotoLibrary()

init(hasSilence: Bool) {
self.hasSilence = hasSilence
<--- here is where is asking to initialize isDismissView, but it should not be needed
}

通过这样做,我能够初始化 isDismissView...

init(hasSilence: Bool, isDismissView: Binding<Bool>?) {
...
self._isDismissView = isDismissView!

但如果我这样做,那么它将在父级中中断,因为我无法将 @State 作为参数传递到 UIHostingController 中,这是必需的。

如果我这样做,我会得到的错误是:

"Accessing State's value outside of being installed on a View. This will result in a constant Binding of the initial value and will not update."

我也在检查@State 变量,即使按钮被触发也不会改变。

干杯,

最佳答案

import SwiftUI

struct ResultViewSilence: View {

///@State needs to be initialized here because it CAN store values
///https://developer.apple.com/documentation/swiftui/state
@State var isDismissView1: Bool = false

///@Binding creates a 2 way connection does NOT store values needs a parent that stores values
///https://developer.apple.com/documentation/swiftui/binding
@Binding var isDismissView2: Bool

var hasSilence: Bool

//let photolibrary = PhotoLibrary() //No code provided

init(hasSilence: Bool, isDismissView2: Binding<Bool> ) {
self.hasSilence = hasSilence
self._isDismissView2 = isDismissView2
}
var body: some View {
VStack{
Text("isDismissView1 = " + isDismissView1.description)
Text("isDismissView2 = " + isDismissView2.description)
}
}
}
struct ParentResultViewSilence: View {
//Parent that can store values
@State var isDismissView2: Bool = true
var body: some View {
ResultViewSilence(hasSilence: false, isDismissView2: $isDismissView2)
}
}
struct ResultViewSilence_Previews: PreviewProvider {
static var previews: some View {
//ResultViewSilence(hasSilence: false, isDismissView2: .constant(true))
ParentResultViewSilence()
}
}

关于ios - 从初始化器返回而不初始化所有存储的属性 - SwiftUI 绑定(bind)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64519493/

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