swiftUI 中的不同行视图 [英] Different row view in swiftUI
本文介绍了swiftUI 中的不同行视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两行,除最后一个元素外,第二行需要与第一行对齐.这是图形表示...
I have two rows and second row needs to be align with first row except the last element. Here is the graphical representation...
我想要的:
这是我的代码:
struct TwoRowView: View {
var body: some View {
VStack {
HStack {
ForEach(0..<6) { i in
Text("\(i)")
.padding(.vertical, 10)
.frame(maxWidth: .infinity)
.background(Color.red)
}
}.padding(.bottom, 5)
HStack {
ForEach(6..<10) { i in
Text("\(i)")
.padding(.vertical, 10)
.frame(maxWidth: .infinity)
.background(Color.red)
}
}
}.padding()
}
}
推荐答案
这是动态检测基本项宽度的可能方法(还引入了一些常量以减少硬编码)
Here is possible approach with dynamic detection of base item width (also introduced some constants to decrease hardcoding)
演示准备&使用 Xcode 12/iOS 14 测试
Demo prepared & tested with Xcode 12 / iOS 14
struct TwoRowView: View {
let last1 = 5 // 7
let last2 = 9 // 12
@State private var baseWidth = CGFloat.zero
var body: some View {
VStack {
HStack {
ForEach(0..<last1+1) { i in
Text("\(i)")
.padding(.vertical, 10)
.frame(maxWidth: .infinity)
.background(GeometryReader {
if i == last1 {
// read dynamic width once by last item
Color.red
.preference(key: ViewWidthKey.self, value: $0.frame(in: .local).size.width)
} else {
Color.red
}
})
}
}.padding(.bottom, 5)
.onPreferenceChange(ViewWidthKey.self) {
self.baseWidth = $0
}
HStack {
ForEach(6..<last2+1) { i in
Text("\(i)")
.padding(.vertical, 10)
.frame(maxWidth: i == last2 ? .infinity : self.baseWidth )
.background(Color.red)
}
}
}.padding()
}
}
struct ViewWidthKey: PreferenceKey {
typealias Value = CGFloat
static var defaultValue = CGFloat.zero
static func reduce(value: inout Value, nextValue: () -> Value) {
value += nextValue()
}
}
这篇关于swiftUI 中的不同行视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文