Search code examples
listviewformattingswiftui

SwiftUI Row Height of List - how to control?


I have a simple List in SwiftUI. Code and Screenshot included below. I would like to reduce the height of each row in the list (so less space between lines and text lines closer together).

I already tried to add a ".frame(height: 20)" to the HStack but it only allows the line spacing to be increased!

Is there a way to do that?

Thanks!

Gerard

import SwiftUI

struct PressureData: Identifiable {
  let id: Int
  let timeStamp: String
  let pressureVal: Int
}

struct ContentView : View {
  @State var pressureList = [
    PressureData(id: 0, timeStamp: "11:49:57", pressureVal: 10),
    PressureData(id: 1, timeStamp: "11:49:56", pressureVal: 8),
    PressureData(id: 2, timeStamp: "11:49:55", pressureVal: 9),
    PressureData(id: 3, timeStamp: "11:49:54", pressureVal: 1),
  ]

  var body: some View {
    VStack {
        Text("Pressure Readings")
            .font(.system(size: 30))
        List(pressureList) { row in
            HStack {
               Spacer()
                Text(row.timeStamp)
                Text("--->")
                Text(String(row.pressureVal))
                Spacer()
            } .frame(height: 30)
        }
    }
  }
}

enter image description here


Solution

  • Use Environment variable to set min Height of the row in the list and after that change the HStack frame height to your desired height.

    Here is the code:

    var body: some View {
        VStack {
            Text("Pressure Readings")
                .font(.system(size: 30))
            List(pressureList) { row in
                HStack {
                    Spacer()
                    Text(row.timeStamp)
                    Text("--->")
                    Text(String(row.pressureVal))
                    Spacer()
                }.frame(height: 10)
            }.environment(\.defaultMinListRowHeight, 10)
        }
    }
    

    Here is the output:

    enter image description here