【发布时间】:2021-07-01 11:56:09
【问题描述】:
我有一个列表,它的单元格内容绑定到一个模型。模型内容取自网络。我使用@StateObject + @ObservableObject + @Published 机制来应用绑定如下:
ViewModel 是:
class ViewModel: ObservableObject {
@Published var employees = [Employee]()
}
视图是:
import SwiftUI
struct PresentView: View {
@StateObject var viewModel = PresenterViewModel("https://www.somelink.com/")
var body: some View {
NavigationView {
List(self.viewModel.employees) { employee in
EmployeeView(name: employee.name,
role: employee.title.rawValue)
}
.listStyle(GroupedListStyle())
.onAppear() {
viewModel.load() // URL combine fetch
}
.navigationBarTitle("Company")
}
}
}
struct EmployeeView: View {
var name: String // <---- I want to attribute it a @Binding
var role: String // <---- I want to attribute it a @Binding
var body: some View {
HStack {
Image(imageName)
VStack {
Text("\(name)")
.font(.headline)
Text("\(role)")
.font(.subheadline)
}
}
}
}
('Employee' 带有几个字符串和一个枚举,并符合 Identifiable and Decodable)
我的问题:
为什么我不能将 EmployeeView 的属性声明为@Binding? (它喊道:“无法将'String'类型的值转换为预期的参数类型'Binding”,我猜他期待调用者的“@State”,但我不能在这里提供)。 毕竟应用@Binding 是有意义的:我的视图模型中已经有了一个事实来源和一个双向绑定。如果我在没有 @Binding 的情况下保留 EmployeeView,这意味着每个单元格内容都将针对每个 List 加载进行复制,这是多余的,因为我的模型中已经有了事实来源。 我做错了什么?
【问题讨论】:
-
既然
EmployeeView没有修改任何东西,为什么你需要它成为Binding?
标签: swiftui swiftui-list