SwiftUI ForEach 'identified(by:)' 已弃用.使用 ForEach(_:id:) 或 List(_:id:) [英] SwiftUI ForEach 'identified(by:)' is deprecated. Use ForEach(_:id:) or List(_:id:)

查看:24
本文介绍了SwiftUI ForEach 'identified(by:)' 已弃用.使用 ForEach(_:id:) 或 List(_:id:)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 XCode 11 beta 4 上,以下内容似乎已被弃用,我不知道如何重写它.有人知道如何使用 ForEach(_:id:) 吗?

On XCode 11 beta 4 the following seems to be deprecated and I don't know how to rewrite this. Does anybody know how to use ForEach(_:id:)?

@State private var showTargets = [
    (id: 1, state: false, x: 109.28, y: 109.28),
    (id: 2, state: false, x: 683, y: 109.28),
    (id: 3, state: false, x: 1256.72, y: 109.28)
]

...

var body: some View {
    HStack {

        ForEach(showTargets.identified(by: \.id)) { item in
            Text(String(item.x))

        }
}

推荐答案

(仍在使用 Xcode 11.0/Swift 5.1)

我还没有下载 Xcode Beta 4,但根据 文档,应该是这样的:

I haven't downloaded Xcode Beta 4 yet, but according to the documentation, it should be something like:

ForEach(showTargets, id: \.id) { item in
    Text(String(item.x))
}

您还可以使用符合 Identifiablestruct(注意,这不适用于元组,因为您无法添加协议一致性):

You can also use a struct that conforms to Identifiable (note that this won't work on tuple because you can't add protocol conformance):

struct Targets: Identifiable {
    var id: Int
    var state: Bool
    var x: Double
    var y: Double
}

let showTargets = [
    Targets(id: 1, state: false, x: 109.28, y: 109.28),
    Targets(id: 2, state: false, x: 683, y: 109.28),
    Targets(id: 3, state: false, x: 1256.72, y: 109.28)
]

ForEach(showTargets) { item in
    Text(String(item.x))
}

这篇关于SwiftUI ForEach 'identified(by:)' 已弃用.使用 ForEach(_:id:) 或 List(_:id:)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆