我遇到了一些麻煩ScrollView,我有以下代碼:
struct ContentView: View {
private enum Constants {
static let cellSize = CGSize(width: 100.0, height: 100.0)
static let rowSpacing: CGFloat = 8.0
}
@State private var rowCount = 1
@State private var contentOffset = CGPoint.zero
private var scrollViewHeight: CGFloat {
CGFloat(rowCount) * Constants.cellSize.height (CGFloat(rowCount) - 1.0) * Constants.rowSpacing
}
var body: some View {
NavigationView {
ScrollView(.horizontal) {
ScrollView {
LazyVStack(spacing: Constants.rowSpacing) {
ForEach((0..<rowCount), id: \.self) { _ in
LazyHStack {
ForEach((1...20), id: \.self) {
Text("Cell \($0)")
.frame(
width: Constants.cellSize.width,
height: Constants.cellSize.height
)
.background(.red)
}
}
}
}
}
.scrollIndicators(.hidden)
}
.ignoresSafeArea(edges: .bottom)
.frame(maxHeight: scrollViewHeight)
.scrollIndicators(.hidden)
.toolbar {
Button("Add Row") {
rowCount = 1
}
Button("Remove Row") {
rowCount -= 1
}
}
.navigationTitle("Test")
}
}
}
由于某種原因,ScrollView內容垂直居中:

我需要內容與頂部對齊。關于如何解決這個問題的任何想法?
uj5u.com熱心網友回復:

您使用VstackandSpacer將水平滾動視圖的區域與頂部對齊。請檢查您想要的實作是否正確。
import SwiftUI
struct ContentView: View {
private enum Constants {
static let cellSize = CGSize(width: 100.0, height: 100.0)
static let rowSpacing: CGFloat = 8.0
}
@State private var rowCount = 1
@State private var contentOffset = CGPoint.zero
private var scrollViewHeight: CGFloat {
CGFloat(rowCount) * Constants.cellSize.height (CGFloat(rowCount) - 1.0) * Constants.rowSpacing
}
var body: some View {
NavigationView {
VStack {
ScrollView(.horizontal) {
ScrollView {
LazyVStack(spacing: Constants.rowSpacing) {
ForEach((0..<rowCount), id: \.self) { _ in
LazyHStack {
ForEach((1...20), id: \.self) {
Text("Cell \($0)")
.frame(
width: Constants.cellSize.width,
height: Constants.cellSize.height
)
.background(.red)
}
}
}
}
}
.scrollIndicators(.hidden)
}
.background(.cyan)
.ignoresSafeArea(edges: .bottom)
.frame(maxHeight: scrollViewHeight)
.scrollIndicators(.hidden)
.toolbar {
Button("Add Row") {
rowCount = 1
}
Button("Remove Row") {
rowCount -= 1
}
}
.navigationTitle("Test")
Spacer()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
uj5u.com熱心網友回復:
您可以洗掉顯式設定框架的行嗎?
//.frame(maxHeight: scrollViewHeight)
并檢查它是否對我有用。

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/516976.html
標籤:IOS迅捷滚动视图
