首页 > 解决方案 > 如何在 SwiftUI 中制作 struct LazyList?

问题描述

我使用 ScrollView+LazyVStack+ForEach 而不是标准列表。

如何对此进行包装?

struct ContentView: View {
    
    @State private var items = ["1", "2", "3"]
    var body: some View {
       LazyList(data: items) { item in
         
       }
    }
}

我试过这段代码:

import SwiftUI

public struct LazyList<Data, ID, Content> where Data : RandomAccessCollection, ID : Hashable {

    public var data: Data
    public var content: (Data.Element) -> Content
    
    var body: some View {
        ScrollView {
            LazyVStack(spacing: 0) {
                ForEach(data, content: content)
            }
        }
    }

错误:

Type of expression is ambiguous without more context

标签: swiftswiftui

解决方案


2021 年,SwiftUI 2

苹果wwdc20-10031说 List 是懒惰的。

列表在 MacOS 上并不懒惰。

(我不知道iOS)

关于问题。你的代码是错误的。这必须有效:

public struct LazyList<Data, ID, Content> where Data : RandomAccessCollection, Data.Element: Identifiable, ID : Hashable, Content: View {

    public var data: Data
    public var content: (Data.Element) -> Content
    
    var body: some View {
        ScrollView {
            LazyVStack(spacing: 0) {
                ForEach(data, content: content)
            }
        }
    }
}

推荐阅读