SwiftUI问题:点击按钮无法向已有ScrollView追加视图
问题分析与解决
你的核心问题是:点击详情按钮时,只是创建了DetailsView的实例,但没有将它添加到当前的视图层级中,所以无论怎么写都不会显示。SwiftUI是声明式UI,视图的显示完全由状态驱动,不是通过在闭包里创建实例来触发的。
具体修复步骤
- 添加一个状态变量控制详情视图的显示:
@State private var showDetails = false - 修改详情按钮的点击逻辑,把创建视图改成切换状态:
Button { showDetails = true } label: { Label("Details", systemImage: "list.bullet.rectangle") .foregroundColor(.blue) } - 在
ScrollView的VStack中,根据状态追加详情视图(放在按钮下方、Spacer之前):if showDetails { DetailsView() .padding(.top, 20) }
额外优化点
- 移除
onChange(of: selectedVendor)里的selectedVendor = newValue,因为@Binding和@State的绑定会自动更新值,这行代码完全多余。 - 移除Picker上的
onTapGesture,因为onAppear已经调用了getVendorNames,重复调用没必要。
修改后的完整代码
import SwiftUI import CoreData struct VendorSelectionView: View { @Environment(\.managedObjectContext) private var viewContext @Environment(\.dismiss) var dismiss @Environment(\.presentationMode) var presentationMode @Binding var chosenProvider: Provider? @State var selectedLocation: Location? @State private var vendorNames: [String] = [] @State private var selectedVendor: String? = nil @State private var showingSheet = false @State private var showDetails = false // 新增状态变量 @State var state: String? @State var zip: String? var body: some View { ScrollView { VStack { HStack { Text("Select Vendor") Picker("Provider", selection: $selectedVendor, content: { ForEach(vendorNames, id: \.self, content: { name in Text(name) }) }) .pickerStyle(MenuPickerStyle()) } .tint(.orange) Button { showDetails = true // 切换状态显示详情 } label: { Label("Details", systemImage: "list.bullet.rectangle") .foregroundColor(.blue) } // 根据状态显示详情视图 if showDetails { DetailsView() .padding(.top, 20) } Spacer() } } .onAppear { getVendorNames() { providers, status in if status { vendorNames = providers } } } .navigationTitle("Add Vendor") .toolbar { ToolbarItem(placement: .navigationBarLeading) { Button(action: { presentationMode.wrappedValue.dismiss() }, label: { HStack(spacing: 2) { Image(systemName: "chevron.backward") .foregroundColor(.black) Button("Back", action: { presentationMode.wrappedValue.dismiss() }) .foregroundColor(.black) } }) } } .navigationViewStyle(StackNavigationViewStyle()) .navigationBarBackButtonHidden(true) } struct DetailsView: View { var body: some View { VStack { Text("Some Details") .font(.headline) // 可以在这里添加更多详情内容 } .frame(maxWidth: .infinity) .padding() .background(Color.gray.opacity(0.1)) .cornerRadius(8) } } func getVendorNames(completionHandler: @escaping ([String], Bool) -> Void) { var names = ["Acme", "Abc"] completionHandler(names, true) } }
内容的提问来源于stack exchange,提问作者vrao
相关产品推荐
相关产品推荐

