一步步学习Swift

SwiftUI学习之ForEach

2022-06-13  本文已影响0人  冷武橘

1、Identifiable

//A class of types whose instances hold the value of an entity with stable identity.
一类类型,其实例持有具有稳定标识的实体的值.
public protocol Identifiable {
associatedtype ID : Hashable
var id: Self.ID { get }
}

  ForEach(items){ item in
        return View
    }

items表示一个集合,经常是一个数组;item参数是闭包content的一个传递参数,自然表示的是一个集合元素
“。
ForEach 是 SwiftUI 中一个用来列举元素,并生成对应 View collection 的类型。它接受一个数组,且数组中的元素必须需要满足 Identifiable 协议。

class Person:Identifiable{
    var id = UUID()
}

struct ContentView: View {
    var body: some View {
        HStack {
            let items:[Person] = [Person(),Person(),Person()]
            ForEach(items) { item
                in
                Text("测试")//return省略
              }
            }
        }
}

2、Hashable

ForEach(items , id: \.self){ i in   return View }  

如果数组元素不满足 Identifiable,我们可以使用 ForEach(_:id:) 来通过某个支持 Hashable 的 key path 获取一个等效的元素是 Identifiable 的数组。

class Person:Hashable{
    var name:String = ""
    static func == (lhs: Person, rhs: Person) -> Bool {
        return lhs.name == rhs.name
    }
    func hash(into hasher: inout Hasher) {
        hasher.combine(name)
    }
}

    var body: some View {
        HStack {
            let items:[Person] = [Person(),Person(),Person()]
            ForEach(items,id: \.self) { item
                in
                Text("测试")//return省略
              }
            }
        }
}
struct ContentView: View {
    var body: some View {
        List {
            let items:[String] = ["0","1","2"]
            ForEach(items,id: \.self) { item
                in
                Text("测试")
              }
            }
        }
}

默认情况下,标准库中的许多类型都符合Hashable:字符串,整数,浮点和布尔值,还有事件集合(even sets)。其他类型(例如,选项(optionals),数组(Array)和范围(Range))在其类型参数实现符合hashable时就会自动变为hashable。

上一篇 下一篇

猜你喜欢

热点阅读