【问题标题】:Same height for all rows in SwiftUI ListSwiftUI 列表中所有行的高度相同
【发布时间】:2020-02-10 07:07:23
【问题描述】:

我正在尝试构建一个List,其中所有行都具有相同的高度

struct ContentView: View {

    @State var content = ["row1", "row2\nrow2\nrow2", "row3"]

    var body: some View {
        List {
            ForEach(0..<content.count, id: \.self) { index in
                Text(self.content[index])
            }
        }
    }
}

Row1 和 row3 应该与 row2 具有相同的高度

【问题讨论】:

  • 您是否尝试为 Text(self.content[index]) 设置 .frame ?
  • @KeyurTailor 不知道框架,高度应该按照列表中最大的高度
  • @KeshuR。不是真的,.defaultMinListRowHeight 可以用来设置最小高度,但我不知道我的行的高度
  • 您需要计算内容中最长字符串的最大height,然后将frame 用于Text 与计算出的height
  • @Kamran 我在这个例子中使用了Text 视图,我的真实行比这复杂得多,几个Text 视图排列成HStackVStack,所以这不会工作

标签: ios swift swiftui


【解决方案1】:

这是一个解决方法。 我使用geometryReader 计算内容高度。一旦我们获得内容的最大高度,在首选项的帮助下更新单元格。

struct TestView: View {
@State var content = ["row1", "row2\nrow2\nrow2", "row3"]
@State var rowHeight: CGFloat = 0

var body: some View {
  List {
      ForEach(0..<content.count, id: \.self) { index in
        Text(self.content[index])
            .frame(minHeight: self.rowHeight)  // set height as max height
            .background(
                GeometryReader{ (proxy) in
                    Color.clear.preference(key: SizePreferenceKey.self, value: proxy.size)  
            })
            .onPreferenceChange(SizePreferenceKey.self) { (preferences) in
                let currentSize: CGSize = preferences
                if (currentSize.height > self.rowHeight) {
                    self.rowHeight = currentSize.height     //As height get change upto max height , put value in self.rowHeight
                }
            }
      }
  }
}
}

struct SizePreferenceKey: PreferenceKey {
    typealias Value = CGSize
    static var defaultValue: Value = .zero

    static func reduce(value: inout Value, nextValue: () -> Value) {
        nextValue()
    }
}

【讨论】:

    猜你喜欢
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2020-11-10
    • 2020-07-14
    • 2019-06-04
    • 2021-04-22
    • 1970-01-01
    相关资源
    最近更新 更多