SwiftUI行高列表-如何控制?


9

我在SwiftUI中有一个简单的List。代码和屏幕截图如下。我想减少列表中每一行的高度(以使行和文本行之间的间距更小)。

我已经尝试向HStack添加一个“ .frame(height:20)”,但是它只允许增加行距!

有没有办法做到这一点?

谢谢!

杰拉德

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

在此处输入图片说明

Answers:


22

使用环境变量设置列表中行的最小高度,然后将HStack框架高度更改为所需的高度。

这是代码:

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

这是输出:

在此处输入图片说明


完美-正是我想要的。感谢您的快速响应,Razib-非常感谢!
杰拉德(Gerard)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.