我正在尝试用SwiftUI构建一个我认为很简单的表单,但在从主体返回的视图(在本例中是Form,但我也尝试过VStack)上收到错误消息“the compiler is unable to type check this expression;try up up the expression to distinct sub sections”。如果我开始删除一些子视图,它似乎解决了,即使我的视图都没有直接返回10个子视图,我认为这是单个视图的限制(除了在ForEach中返回的视图)。
import SwiftUI
struct CreateDispatchView: View {
@State private var customerId: Int = 0
@State private var name: String = ""
@State private var phone: String = ""
@State private var description: String = ""
@State private var priorityId: Int = 0
@State private var callTypeId: Int = 0
@State private var bay: String = ""
@State private var poTicket: String = ""
@State private var outOfChemicals: Bool = false
@State private var isReturnCall: Bool = false
var body: some View {
Form { // <-- Error is shown here
Section {
Picker("Customer", selection: $customerId) {
ForEach(0 ..< 10) {
Text("Customer \($0)")
}
}
TextField("Name", text: $name)
TextField("Phone", text: $phone)
TextField("Description", text: $description)
TextField("Bay", text: $bay)
TextField("PO ticket", text: $poTicket)
}
Section {
Picker("Priority", selection: $priorityId) {
ForEach(0 ..< 2) {
Text("Priority \($0)")
}
}
Picker("Call type", selection: $callTypeId) {
ForEach(0 ..< 3) {
Text("Call type \($0)")
}
}
}
Section {
Toggle(isOn: $outOfChemicals) {
Text("Out of chemicals")
}
Toggle(isOn: $isReturnCall) {
Text("Is return call")
}
}
}
}
}
struct CreateDispatchView_Previews: PreviewProvider {
static var previews: some View {
CreateDispatchView()
}
}
发布于 2019-10-17 14:10:17
大型嵌套ViewBuilder
表达式的处理是当前swift编译器中的一个弱点。不过,一般来说,它建议“尝试将表达式拆分成不同的子部分”是一个很好的建议:将这些整体ViewBuilder
表达式重构为单独的动态变量是提高性能的好方法(此外,它还有助于隔离实际错误)。
下面是一个如何重构代码以成功编译的示例:
struct CreateDispatchView: View {
@State private var customerId: Int = 0
@State private var name: String = ""
@State private var phone: String = ""
@State private var description: String = ""
@State private var priorityId: Int = 0
@State private var callTypeId: Int = 0
@State private var bay: String = ""
@State private var poTicket: String = ""
@State private var outOfChemicals: Bool = false
@State private var isReturnCall: Bool = false
var body: some View {
Form {
customerSection
prioritySection
infoSection
}
}
private var customerSection: some View {
Section {
Picker("Customer", selection: $customerId) {
ForEach(0 ..< 10) {
Text("Customer \($0)")
}
}
TextField("Name", text: $name)
TextField("Phone", text: $phone)
TextField("Description", text: $description)
TextField("Bay", text: $bay)
TextField("PO ticket", text: $poTicket)
}
}
private var prioritySection: some View {
Section {
Picker("Priority", selection: $priorityId) {
ForEach(0 ..< 2) {
Text("Priority \($0)")
}
}
Picker("Call type", selection: $callTypeId) {
ForEach(0 ..< 3) {
Text("Call type \($0)")
}
}
}
}
private var infoSection: some View {
Section {
Toggle(isOn: $outOfChemicals) {
Text("Out of chemicals")
}
Toggle(isOn: $isReturnCall) {
Text("Is return call")
}
}
}
}
https://stackoverflow.com/questions/58434117
复制