首页 > 解决方案 > 无法转换“已发布”类型的值.Publisher'到预期的参数类型'绑定'

问题描述

尝试编译以下代码时:

class LoginViewModel: ObservableObject, Identifiable {
    @Published var mailAdress: String = ""
    @Published var password: String = ""
    @Published var showRegister = false
    @Published var showPasswordReset = false

    private let applicationStore: ApplicationStore

    init(applicationStore: ApplicationStore) {
        self.applicationStore = applicationStore
    }

    var passwordResetView: some View {
        PasswordResetView(isPresented: $showPasswordReset) // This is where the error happens
    }
}

PasswordResetView 如下所示:

struct PasswordResetView: View {
    @Binding var isPresented: Bool
    @State var mailAddress: String = ""
    
    var body: some View {
            EmptyView()
        }
    }
}

我收到错误编译错误

Cannot convert value of type 'Published<Bool>.Publisher' to expected argument type 'Binding<Bool>'

如果我从 LoginViewModel 类之外使用发布的变量,它就可以正常工作:

struct LoginView: View {
    @ObservedObject var viewModel: LoginViewModel

    init(viewModel: LoginViewModel) {
      self.viewModel = viewModel
    }
    
    var body: some View {
            PasswordResetView(isPresented: self.$viewModel.showPasswordReset)
    }
}

有什么建议我在这里做错了吗?我有机会从所属类内部将已发布的变量作为绑定传递吗?

谢谢!

标签: iosswiftswiftuicombine

解决方案


** 对 Combine 和 SwiftUI 来说还是新手,所以不确定是否有更好的方法来处理 **

您可以从发布者初始化绑定。

https://developer.apple.com/documentation/swiftui/binding/init(get:set:)-6g3d5

let binding = Binding(
    get: { [weak self] in
        (self?.showPasswordReset ?? false)
    },
    set: { [weak self] in
        self?.showPasswordReset = $0
    }
)

PasswordResetView(isPresented: binding)


推荐阅读