ios-如何返回 View 以编辑其属性?
发布时间:2022-09-08 23:34:39 365
相关标签: # android
我正在创建一个返回其编辑器视图的类。但是遇到了错误
无法将“Published.Publisher”类型的值转换为预期的参数类型“Binding”
这是 Playgrounds 的简单测试代码。
import SwiftUI
import PlaygroundSupport
struct EditorView: View {
@Binding var text: String
var body: some View {
HStack {
Text("Name:")
TextField("Jerry", text: $text)
}
}
}
class MyModel: ObservableObject {
@Published var name: String = "Tom"
func editorView() -> some View {
EditorView(text: $name) // [ERROR] Cannot convert value of type 'Published.Publisher' to expected argument type 'Binding'
}
}
struct ContentView: View {
@StateObject var model: MyModel = .init()
var body: some View {
model.editorView()
}
}
struct ContentView_Preview: PreviewProvider {
static var previews: some View {
ContentView()
.previewLayout(.fixed(width: 375, height: 400))
}
}
let viewController = UIHostingController(rootView: ContentView())
let nav = UINavigationController(rootViewController: viewController)
PlaygroundPage.current.liveView = nav
怎么了?
2022.03.23新增
我试着在没有绑定的情况下创建一个视图,它是有效的。我认为这个类可以用它的属性创建一个视图。但无法通过@Binding。
import SwiftUI
import PlaygroundSupport
struct EditorView: View {
@Binding var text: String
var body: some View {
HStack {
Text("Name:")
TextField("Jerry", text: $text)
}
}
}
// Just display the name parameter
struct DispView: View {
let name: String
var body: some View {
Text(name)
}
}
class MyModel: ObservableObject {
@Published var name: String = "Tom"
@ViewBuilder
func editorView() -> some View {
// EditorView(text: $name) // Error at this line.
DispView(name: name) // Pass the property.
}
}
struct ContentView: View {
@StateObject var model: MyModel = .init()
var body: some View {
model.editorView()
}
}
struct ContentView_Preview: PreviewProvider {
static var previews: some View {
ContentView()
.previewLayout(.fixed(width: 375, height: 400))
}
}
let viewController = UIHostingController(rootView: ContentView())
let nav = UINavigationController(rootViewController: viewController)
PlaygroundPage.current.liveView = nav
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报