Sorin Lica
Sorin Lica

Reputation: 7636

Add view in a SwiftUI Form without a Section

I did not succeed to add a view in a Form without being embedded in a Section, so I tried to make the Section "invisible" setting for Section the same background the Form has, but there are separators which I also have to hide, I found this UITableView.appearance().separatorColor = UIColor(named: "Background") which sets for separators the same colour the Form background has, but the problem is that this applies on the whole Form and I do not want that :(

Any idea how I could add a view in a Form without a Section or how to "hide" the section without to influence the other Sections in the 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"))
        }
    }
}

enter image description here

Upvotes: 6

Views: 1975

Answers (2)

Cameron McBroom
Cameron McBroom

Reputation: 527

A little late but might help some others:

  1. Place your content in a VStack (if you have more than a single element)
  2. Set the .listRowInset to EdgeInsets()
  3. Set the frame max width and height OR use spacers

Using frame:

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

Using spacers (this solution adds slightly more padding on the top and bottom):

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

enter image description here

Full code:

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")
}

Upvotes: 8

Usama Azam
Usama Azam

Reputation: 433

Add this line in init()

 UITableView.appearance().separatorStyle = .none

Upvotes: 0

Related Questions