51

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

Gerard
  • 1,807
  • 4
  • 13
  • 20

1 Answers1

117

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

Grimxn
  • 22,115
  • 10
  • 72
  • 85
Razib Mollick
  • 4,617
  • 2
  • 22
  • 20