【发布时间】:2020-02-07 20:18:48
【问题描述】:
以下示例代码应在 ScrollView 内生成一个 RoundedRectangle 网格。使用 NavigationBar 中的按钮,您可以更改行数和列数。它在 iPad 上效果最好,因为它的屏幕更大。
当您运行此代码时,您会看到(或者至少,我看到了)ScrollView 的内容没有很好地居中。当你添加一些行和列时,你看不到最上面和最左边的,并且在底部和右边有一些空白区域。
是否有更多人遇到此问题?有没有人找到解决方案?有人知道创建具有灵活宽度和高度的可滚动网格的另一种方法吗?
import SwiftUI
struct ContentView: View {
@State var x: Int = 5
@State var y: Int = 5
var body: some View {
NavigationView {
ScrollView([.horizontal, .vertical]) {
VStack(spacing: 8) {
ForEach(0 ..< self.y, id: \.self) { yCoor in
HStack(spacing: 8) {
ForEach(0 ..< self.x, id: \.self) { xCoor in
RoundedRectangle(cornerRadius: 10)
.frame(width: 120, height: 120)
.foregroundColor(.orange)
.overlay(Text("(\(xCoor), \(yCoor))"))
}
}
}
}
.border(Color.green)
}
.border(Color.blue)
.navigationBarTitle("Contents of ScrollView misplaced", displayMode: .inline)
.navigationBarItems(
leading: HStack(spacing: 16) {
Text("x:")
.bold()
Button(action: { if self.x > 0 { self.x -= 1 } }) {
Image(systemName: "minus.circle.fill")
.imageScale(.large)
}
Button(action: { self.x += 1 }) {
Image(systemName: "plus.circle.fill")
.imageScale(.large)
}
},
trailing: HStack(spacing: 16) {
Text("y:")
.bold()
Button(action: { if self.y > 0 { self.y -= 1 } }) {
Image(systemName: "minus.circle.fill")
.imageScale(.large)
}
Button(action: { self.y += 1 }) {
Image(systemName: "plus.circle.fill")
.imageScale(.large)
}
}
)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
【问题讨论】:
-
以下关于网格和对齐的主题可能对您有用SwiftUI How to align a view that's larger than screen width
-
我也有同样的问题。但不是用网格,而是用图像。我想问题来自
ScrollView([.horizontal, .vertical]),但我不明白为什么。