Home > Software design >  How do I add a border to a cell group in an InsetGroupedListStyle List in SwiftUI?
How do I add a border to a cell group in an InsetGroupedListStyle List in SwiftUI?

Time:08-08

Given the following View

import SwiftUI

struct ContentView: View {
  
  init() {
    UITableViewCell.appearance().backgroundColor = .black
    UITableView.appearance().backgroundColor = .black
  }
  
  var body: some View {
    List {
      Text("foo").listRowBackground(Color.gray)
      Text("bar").listRowBackground(Color.gray)
      Text("foo").listRowBackground(Color.gray)
      Text("bar").listRowBackground(Color.gray)
    }
    .listStyle(.insetGrouped)
  }
}

which renders as follows

enter image description here

How would one add a border around the list elements following the rounded corner of the InsetGroupedListStyle like this red border

enter image description here

I have tried adding borders and shadows to either the List or the cells but they never match an insetGrouped cell "block".

CodePudding user response:

Add border will not work in this way because Apple have standards for List layouts and we can't modify those. To achieve your requirement we have to do our own customization by dividing them into sections and keeping VStack in each section.

enter image description hereplease check my below code which provides border to each section.

var body: some View {
      List {
          Section {
              VStack {
                  ForEach(items, id: \.self) { item in
                      HStack {
                          Text(item)
                          Spacer()
                      }
                      .padding(8)
                      
                      if items.last != item {
                          Divider()
                      }
                  }
              }
              .overlay(RoundedRectangle(cornerRadius: 10, style: .circular).stroke(Color(uiColor: .tertiaryLabel), lineWidth: 1)
                              )
          }
      }
      .listStyle(InsetListStyle())
      
  }
  • Related