首页 > 解决方案 > 在没有部分的 SwiftUI 表单中添加视图

问题描述

我没有成功地在 a 中添加视图Form而不嵌入 a 中Section,因此我尝试为具有相同背景的Section“不可见”设置进行设置,但是我还必须隐藏分隔符,我发现它设置为分隔符与背景颜色相同,但问题是这适用于整体,我不希望这样:(SectionFormUITableView.appearance().separatorColor = UIColor(named: "Background")FormForm

知道如何在Form没有 a的情况下添加视图,Section或者如何“隐藏”该部分而不影响 中的Sections另一个Form

struct ContentView: View {

    init() {
        UITableView.appearance().separatorColor = UIColor(named: "Background")
    }

    var body: some View {

        Form {
            Section {
                Text("text1")
                Text("text2")
                Text("text3")
            }

            Text("View without section")
                .font(.title)
                .listRowBackground(Color("Background"))
        }
    }
}

在此处输入图像描述

标签: iosswiftui

解决方案


有点晚了,但可能会帮助其他一些人:

  1. 将您的内容放在 VStack 中(如果您有多个元素)
  2. 设置.listRowInsetEdgeInsets()
  3. 设置框架最大宽度和高度或使用垫片

使用框架:

VStack(alignment: .leading) {
    Text("Title").font(.headline)
    Text("Subheadline").font(.subheadline)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
.listRowInsets(EdgeInsets())
.background(Color(UIColor.systemGroupedBackground))

使用垫片(此解决方案在顶部和底部添加了更多的填充):

HStack {
    VStack(alignment: .leading) {
        Spacer()
        Text("Title").font(.headline)
        Text("Subheadline").font(.subheadline)
        Spacer()
    }
    Spacer()
}
.listRowInsets(EdgeInsets())
.background(Color(UIColor.systemGroupedBackground))

在此处输入图像描述

完整代码:

NavigationView {
    Form {
        VStack(alignment: .leading) {
            Text("Testing a title").font(.headline)
            Text("Testing a subheadline").font(.subheadline)  
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
        .listRowInsets(EdgeInsets())
        .background(Color(UIColor.systemGroupedBackground))
                
        Section(header: Text("Title and Category").bold()) {
           TextField("Title", text: $title)
           TextField("Category", text: $title)        
        }
    }
    .navigationTitle("Test Form")
}


推荐阅读