"减少行间距真的很棘手,请尝试"
struct ContentView: View {
@State var data : [String] = ["first","second","3rd","4th","5th","6th"]
var body: some View {
VStack {
ScrollView {
ForEach(data, id: \.self) { item in
VStack(alignment: .leading, spacing: 0) {
Color.red.frame(height: 1)
Text("\(item)").font(.largeTitle)
.background(Color.yellow)
}.background(Color.green)
.padding(.leading, 10)
.padding(.bottom, -25)
.frame(maxWidth: .infinity)
}
}
}
}
}
它使用ScrollView而不是List和负填充。
![enter image description here](https://istack.dev59.com/DkAiS.webp)
我没有找到任何基于List的解决方案,我们必须要求苹果发布xxxxStyle协议和底层结构。
更新
这个负的padding值怎么样?肯定取决于我们行内容的高度,不幸的是,还取决于SwiftUI的布局策略。让我们尝试一些更动态的内容!(我们使用零填充来演示需要解决的问题)
struct ContentView: View {
@State var data : [CGFloat] = [20, 30, 40, 25, 15]
var body: some View {
VStack {
ScrollView {
ForEach(data, id: \.self) { item in
VStack(alignment: .leading, spacing: 0) {
Color.red.frame(height: 1)
Text("\(item)").font(.system(size: item))
.background(Color.yellow)
}.background(Color.green)
.padding(.leading, 10)
.frame(maxWidth: .infinity)
}
}
}
}
}
![enter image description here](https://istack.dev59.com/yBJFj.webp)
显然,行间距不是固定值!我们必须为每一行分别计算它。
下一个代码片段展示了基本思路。我使用了全局字典(用于存储每一行的高度和位置),并尽量避免使用高阶函数和/或一些高级的SwiftUI技术,以便更容易理解策略。所需的填充仅在.onAppear闭包中计算一次。
import SwiftUI
var _p:[Int:(CGFloat, CGFloat)] = [:]
struct ContentView: View {
@State var data : [CGFloat] = [20, 30, 40, 25, 15]
@State var space: [CGFloat] = []
func spc(item: CGFloat)->CGFloat {
if let d = data.firstIndex(of: item) {
return d < space.count ? space[d] : 0
} else {
return 0
}
}
var body: some View {
VStack {
ScrollView {
ForEach(data, id: \.self) { item in
VStack(alignment: .leading, spacing: 0) {
Color.red.frame(height: 1)
Text("\(item)")
.font(.system(size: item))
.background(Color.yellow)
}
.background(
GeometryReader { proxy->Color in
if let i = self.data.firstIndex(of: item) {
_p[i] = (proxy.size.height, proxy.frame(in: .global).minY)
}
return Color.green
}
)
.padding(.leading, 5)
.padding(.bottom, -self.spc(item: item))
.frame(maxWidth: .infinity)
}.onAppear {
var arr:[CGFloat] = []
_p.keys.sorted(by: <).forEach { (i) in
let diff = (_p[i + 1]?.1 ?? 0) - (_p[i]?.1 ?? 0) - (_p[i]?.0 ?? 0)
if diff < 0 {
arr.append(0)
} else {
arr.append(diff)
}
}
self.space = arr
}
}
}
}
}
运行我得到的代码
![enter image description here](https://istack.dev59.com/qsHuW.webp)