swiftui - 我可以创建一个无限滚动但具有固定值的 ScrollView 吗?

标签 swiftui

给定如下所示的 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/

相关文章:

ios - SwiftUI 中 UICollectionViewController 的替代品是什么?

swift - 如何使用 combine Publisher 更改线程?

SwiftUI - TabView with NavigationView 生成灰色区域

ios - 在 SwiftUI 中拖动分隔符

ios - SwiftUI 中的动态过滤器(谓词)

ios - SKCloudServiceController().requestUserToken 在 iOS 14.2 上卡住

swift - SwiftUI中的图片全屏宽度

ios - 将 SwiftUI 按钮绑定(bind)到 AnySubscriber,例如 RxCocoa 的按钮点击

swiftui - 正确对齐VStack和HStack

image - 使用 DispatchQueue 在 SwiftUI 中异步加载图像