SwiftUI中点击加号按钮添加文本后无法显示内容的问题
修复SwiftUI中点击Add后内容不显示的问题
问题根源
你的代码存在几个关键问题导致输入内容无法显示:
List闭包内没有任何渲染内容,即使数组有数据也不会展示ZStack层级覆盖了List,导致列表被背景元素完全挡住- Sheet的
onDismiss和Add按钮中重复执行添加元素逻辑,可能引发数据不一致 - TextField的占位符错误绑定了动态变量,应该使用静态提示文本
修复后的完整代码
struct LandingView: View { @State private var newLandingName: String = "" @State private var isAddingLanding = false @State private var landings: [String] = [] var body: some View { NavigationView { ZStack { // 背景元素 Color.blue.ignoresSafeArea() Circle() .scale(1.7) .foregroundColor(.yellow.opacity(0.60)) Circle() .scale(1.3) .foregroundColor(.blue.opacity(0.50)) VStack(spacing: 20) { // 顶部标题与加号按钮 HStack { Text("添加着陆点!") .bold() .font(.largeTitle) .padding() .foregroundColor(.white) // 提升文字可读性 Spacer() Button(action: { isAddingLanding = true }) { Image(systemName: "plus") .resizable() .frame(width: 20, height: 20) .foregroundColor(.white) } .frame(width: 40, height: 40) .background(Color.blue) .cornerRadius(20) .padding(.trailing, 10) } // 着陆点列表(核心修复:添加内容渲染) List(landings, id: \.self) { landing in Text(landing) .foregroundColor(.black) } .background(Color.white.opacity(0.8)) .cornerRadius(10) .padding(.horizontal) } } .navigationBarTitle("着陆点") .sheet(isPresented: $isAddingLanding) { VStack(spacing: 20) { TextField("输入着陆点名称", text: $newLandingName) .textFieldStyle(RoundedBorderTextFieldStyle()) .padding() Button("添加") { // 去除空格后校验空值 guard !newLandingName.trimmingCharacters(in: .whitespaces).isEmpty else { isAddingLanding = false return } landings.append(newLandingName) newLandingName = "" isAddingLanding = false } .padding() .frame(maxWidth: .infinity) .background(Color.blue) .foregroundColor(.white) .cornerRadius(10) .padding(.horizontal) } .padding() } } } } // 若需保留LandingNameView的示例实现 struct LandingNameView: View { let newLandingName: String var body: some View { if !newLandingName.isEmpty { Text("当前输入: \(newLandingName)") .foregroundColor(.white) .padding() } } }
关键修改说明
- 修复List内容渲染:在
List闭包中添加Text(landing),确保数组中每个元素都能被展示 - 调整布局层级:将
List放入ZStack内的VStack中,避免被背景元素覆盖,同时添加半透明白色背景增强可读性 - 简化添加逻辑:仅在Add按钮中处理数据添加,移除
onDismiss中的重复逻辑,避免重复添加问题 - 修正TextField占位符:将动态变量替换为静态提示文本,同时增加去除空格后的空值校验
- 优化按钮样式:给加号按钮添加背景色,提升视觉效果和交互体验
内容的提问来源于stack exchange,提问作者allanrulezdood
相关产品推荐
相关产品推荐

