iOS SwiftUI - 无法将ObservedObject类型的值转换

4
我有一个视图:
struct CreateAccountButton : View {
    
    @Binding var viewRouter: ViewRouter

    var body: some View{
        Button(action: {
            withAnimation {
                viewRouter.currentPage = .register
            }
            
        }) {
            
            Text("create_account")
                .padding(.vertical)
                .frame(maxWidth: .infinity)
                .foregroundColor(Color("ColorText"))
                .overlay(
                    RoundedRectangle(cornerRadius: 5)
                        .stroke(Color.white, lineWidth: 0))
                
        }
        .background(Color("BtnGreenBG"))
        .frame(minWidth: 0, maxWidth: .infinity)
        .cornerRadius(5)
        .padding(.top, 12)
    }
}

我需要传递在主视图中创建的viewRouter:

@StateObject var viewRouter: ViewRouter

我尝试过:

CreateAccountButton(viewRouter: $viewRouter)

并获得:

Cannot convert value of type 'ObservedObject<ViewRouter>.Wrapper' to expected argument type 'Binding<ViewRouter>'

我是一个新手,对iOS/SwiftUI不熟悉,不理解这个错误。

根据这个答案:

如何在SwiftUI中将ObservedObject类型的值转换为Binding?

我做出了更改:

@Binding var viewRouter: ViewRouter

为了

@ObservedObject var viewRouter: ViewRouter

在CreateAccountButton中,但它仍然无法正常工作。

与Kotlin相比,SwiftUI/Swift是一场缺乏直觉的噩梦 :(

请帮忙。


为什么你有这个路由器对象?看起来不对。 - malhal
2个回答

7
ObservableObject是一个引用类型,因此我们可以直接通过引用传递它,不需要绑定。
struct CreateAccountButton : View {
    
    let viewRouter: ViewRouter     // << regular property

// if needed to observe it internally, ie. body (not closures) 
// contains router's property usage

//  @ObservedObject var viewRouter: ViewRouter


// ...

并调用

CreateAccountButton(viewRouter: viewRouter) // inject reference

1
不要传递整个对象,而是只传递您的虚拟机中的特定数据。
CreateAccountButton(viewRouter: $viewRouter.currentPage)

@Binding var currentPage: Bool 

在你的CreateAccountButton中。

我认为我需要在CreateAccountButton内创建一个新的ViewRouter对象,这将消除ViewRouter的目的,我可以使用它在页面之间切换,而不会出现NavigationView的愚蠢默认回溯。 - user19591083
NavigationView是必须的。你无法仅凭变量在页面之间切换。除了NavigationView之外,其他任何东西都只是堆叠在一起或者遮盖的堆栈。 - Steven-Carrot
我使用NavigationView传递viewRouter,通过它可以在页面之间进行切换。使用基本的NavigationView,我无法从第1页到第2页,然后从第2页到第3页并关闭第2页,但使用viewRouter则可以。在Android中,您可以轻松地完成此操作而无需解决问题,而iOS开发有时确实很愚蠢。 - user19591083

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接