SwiftUI学习之ForEach

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。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 学习文章 文集:Hacking with iOS: SwiftUI Edition[https://www.jia...
    xmb阅读 4,591评论 3 14
  • 持续更新中...... swift官方文档 swift官方文档(英文) 协议 swift主要基于协议编程的,所以协...
    云上听风阅读 3,300评论 2 4
  • 最前面想说的话 转眼已经是2020年10月了,2020已经过去大半了,上半年的计划已经完成,所以下半年的学习应该提...
    微笑_d797阅读 2,774评论 2 2
  • SwiftUI要求 iOS13.0+ 快捷键 control + option + 点击:出现属性编辑器 comm...
    余青松阅读 6,419评论 1 11
  • 原文链接[https://developer.apple.com/videos/play/wwdc2021/100...
    Oceanj阅读 2,980评论 0 2