我在SwiftUI中对齐导航标题和内容视图遇到了困难。使用集合视图流布局,在UIKit中很容易实现此操作。
n.b. 这是一个试验性项目,我正在使用iOS 15。
我尝试了许多不同的方法:
1. 使用列表
在iPhone 12 Max上,这为我们提供了导航标题、标头和单元格之间正确的对齐,但在iPhone 12上却不行。
滚动视图不像Apple Music应用程序那样延伸到边缘。
有没有一种方法可以解决滚动视图的问题?
iPhone 12 Max截图
iPhone 12截图
代码
var body: some View {
NavigationView {
GeometryReader { proxy in
let cellWidth = proxy.size.width * 0.4
List {
ForEach(0...10, id: \.self) { rowIndex in
Section(header: Text("Unknown").font(.title2).redacted(reason: .placeholder)) {
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack(alignment: .top, spacing: 16) {
ForEach(0...10, id: \.self) { index in
VStack(alignment: .leading, spacing: 2) {
RoundedRectangle(cornerRadius: 8)
.foregroundColor(.red)
.frame(width: cellWidth, height: cellWidth)
VStack(alignment: .leading, spacing: 2) {
Text("Example")
.foregroundColor(.primary)
.font(.subheadline)
.lineLimit(1)
.redacted(reason: .placeholder)
Text("Example")
.foregroundColor(.secondary)
.font(.subheadline)
.lineLimit(1)
.redacted(reason: .placeholder)
}
}
}
}
}
}
}
}
.listStyle(InsetListStyle())
.navigationBarTitle("Experimental")
}
}
}
2. 使用VStack和padding...
- 似乎没有一种直接的方法来使
VStack
和标题的第一个单元格对齐。例如,在 iPhone 12 Pro Max 上,20 的填充值可以实现正确的对齐,但在 iPhone 12 上,使用相同的填充值会有大约 2 像素的偏差。 - 现在,水平滚动视图通过仅对第一个单元格进行填充而按预期工作。
iPhone 12 Max 屏幕截图
iPhone 12 屏幕截图
代码
var bodyUsingVStack: some View {
NavigationView {
GeometryReader { proxy in
let cellWidth = proxy.size.width * 0.4
ScrollView {
VStack(alignment: .leading, spacing: 16) {
ForEach(0...10, id: \.self) { rowIndex in
Section(
header: Text("Unknown")
.font(.title2)
.padding(.leading, 20)
// .redacted(reason: .placeholder)
) {
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack(alignment: .top, spacing: 16) {
ForEach(0...10, id: \.self) { index in
VStack(alignment: .leading, spacing: 2) {
RoundedRectangle(cornerRadius: 8)
.foregroundColor(.red)
.frame(width: cellWidth, height: cellWidth)
VStack(alignment: .leading, spacing: 2) {
Text("Example")
.foregroundColor(.primary)
.font(.subheadline)
.lineLimit(1)
.redacted(reason: .placeholder)
Text("Example")
.foregroundColor(.secondary)
.font(.subheadline)
.lineLimit(1)
.redacted(reason: .placeholder)
}
}
.padding(.leading, index == 0 ? 22 : 0)
}
}
}
}
}
}
}
.listStyle(InsetListStyle())
.navigationBarTitle("Experimental")
}
}
}
- 其他想法
- 使用对齐指南似乎不起作用
- 想要扩展底层的UINavigation视图,以捕获标题的确切位置以计算正确的填充。
- 测试所有iOS设备并预先确定每个设备的正确填充值...
肯定有更简单的方法,SwiftUI 提供了很多灵活性,但我们经常会因为做一些琐碎的事情而卡上数小时或数天。
ScrollView
全宽,我会将这个答案保持可见。 - George