gpt4 book ai didi

ios - SwiftUI 列表中所有行的高度相同

转载 作者:行者123 更新时间:2023-12-01 16:01:21 26 4
gpt4 key购买 nike

我正在尝试构建一个 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 具有相同的高度
enter image description here

最佳答案

这是一个解决方法。
我已经使用 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()
}
}

output

关于ios - SwiftUI 列表中所有行的高度相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60145559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com