ios - 无法转换“已发布”类型的值.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)
}
}
有什么建议我在这里做错了吗?我有机会从所属类内部将已发布的变量作为绑定传递吗?
谢谢!
解决方案
** 对 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)
推荐阅读
- ruby-on-rails - 出于测试目的调用外部文件的语法
- sql - 使用 SQL 的 MarkLogic 日期时间
- routing - 如果我的 IP(在本地网络中)不是唯一的,外部设备如何寻址我?
- android - 线性布局开关不起作用
- c# - 错误消息“没有为此对象定义无参数构造函数”
- javascript - 离子离子日期时间:如何设置默认选择器值
- python - 读取数据集并使用 Pandas 对一些信息进行分组
- php - 在 phpunit.xml 中使用 conn:sqlite value::memory: 而不是 conn:mysql db:testing 时,一些测试开始失败?
- java - 如何将两个 SeekBar 的两个值相加并在文本视图中打印?
- ios - 无法单击选项卡栏控制器中的更多选项列表