Search code examples
iosswiftlistviewswiftui

How to create spacing between items in a SwiftUI List view?


I can't seem to find a way to create spacing between List items. Maybe I shouldn't put in a list in the first place?

enter image description here

What do you think?

This the code that generates the view:

struct ContentView: View {
    
    @ObservedObject var ratesVM = RatesViewModel()
    
    init() {
        UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.white]
        UITableView.appearance().backgroundColor = UIColor.init(named: "midnight blue")
        UITableViewCell.appearance().backgroundColor = .green
        UITableView.appearance().separatorStyle = .none
    }
    
    var body: some View {
        
        NavigationView {
            List (ratesVM.ratesList, id: \.self) { rate in
                    Image(systemName: "plus")
                    
                    Button(action: {print("pressed")}) {
                        Text(rate.hebrewCurrencyName)
                }
            }
            .navigationBarTitle("המרות מטבע")
            .navigationBarItems(leading:
                Button(action: {
                    print("button pressed")
                    self.ratesVM.callService()
                }) {
                    Image(systemName: "plus")
                        .foregroundColor(Color.orange)})
        }.environment(\.layoutDirection, .rightToLeft)
    }
}

Solution

  • You can define the minimum list row height to be bigger so you'll have more separation between rows.

    List (ratesVM.ratesList, id: \.self) { rate in
           Image(systemName: "plus")
           Button(action: {print("pressed")}) {
                        Text(rate.hebrewCurrencyName)
           }
    }.environment(\.defaultMinListRowHeight, 50) //minimum row height
    

    Alternatively you can build your row as a HStack and specify a frame height.

    List (ratesVM.ratesList, id: \.self) { rate in
        HStack {
           Image(systemName: "plus")
           Button(action: {print("pressed")}) {
              Text(rate.hebrewCurrencyName)
           }
        }.frame(height: 50) //your row height 
    }.environment(\.defaultMinListRowHeight, 20) 
    

    Or as a VStack and and use Spacers

    List (ratesVM.ratesList, id: \.self) { rate in
        VStack{
            Spacer()
            HStack {
               Image(systemName: "plus")
               Button(action: {print("pressed")}) {
                  Text(rate.hebrewCurrencyName)
               }
            }
            Spacer()
        }.frame(height: 50)
    }.environment(\.defaultMinListRowHeight, 20)