给定如下所示的 ScrollView 如果我有一个像下面这样的ScrollView,我可以在1到10的CircleView之后再显示1到10吗?
我想使用相同的 1-10 值并在 10 之后显示 1、2、3....10。我想使用相同的 1...10 值并显示 1、2、3... 10 后 10。
struct ContentView: View {
var body: some View {
VStack {
Divider()
ScrollView(.horizontal) {
HStack(spacing: 10) {
ForEach(0..<10) { index in
CircleView(label: "\(index)")
}
}.padding()
}.frame(height: 100)
Divider()
Spacer()
}
}
}
struct CircleView: View {
@State var label: String
var body: some View {
ZStack {
Circle()
.fill(Color.yellow)
.frame(width: 70, height: 70)
Text(label)
}
}
}
引用: https://www.simpleswiftguide.com/how-to-create-horizontal-scroll-view-in-swiftui/
最佳答案
您可以使用 LazyHStack
在前一个项目出现时添加一个新项目:
// Use `class`, since you don't want to make a copy for each new item
class Item {
var value: Int
// Other properties
init(value: Int) {
self.value = value
}
}
struct ItemWrapped: Identifiable {
let id = UUID()
var wrapped: Item
}
struct ContentView: View {
static let itemRaw = (0..<10).map { Item(value: $0) }
@State private var items = [ItemWrapped(wrapped: itemRaw.first!)]
@State private var index = 0
var body: some View {
VStack {
Divider()
// Scroll indicator might be meaningless?
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack(spacing: 10) {
ForEach(items) { item in
CircleView(label: item.wrapped.value.formatted())
.onAppear {
// Index iteration
index = (index + 1) % ContentView.itemRaw.count
items.append(
ItemWrapped(wrapped: ContentView.itemRaw[index]))
}
}
}.padding()
}.frame(height: 100)
Divider()
Spacer()
}
}
}
关于swiftui - 我可以创建一个无限滚动但具有固定值的 ScrollView 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68409874/