SwiftUI ForEach类型“ _”没有成员“ id”

时间:2019-07-19 13:52:49

标签: swiftui

当我在ForEach中使用自定义视图时,我得到类型'_'没有成员'id'错误。当我使用Text(item.x)而不是自定义视图时,它将编译并运行。我想念什么?

@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 {
    Group {

        ForEach(showTargets, id: \.id) { item in
            Text(String(item.x))
            // Using CustomView(x: item.x, y: item.y, f: {}) instead does not work
        }
}

自定义视图:

struct CustomView : View {

    @State private var color = Color.white
    @State private var animate = false


    internal var x: CGFloat
    internal var y: CGFloat
    internal var f: ()->()
    internal let w: CGFloat = 60
    internal let h: CGFloat = 60

    private let width = -1366/2
    private let height = -1024/2

    var body: some View {
        Button(action: {
            self.animate.toggle()
            if self.color == Color.green {
                self.color = Color.white
            }
            else {
                self.color = Color.green
                self.f()
            }
        }, label: {
            Ellipse()
                .fill(self.color)
                .scaleEffect(self.animate ? 1.2 : 1)
                .animation(Animation.easeInOut)

        }).position(x: self.x + self.w/2, y: self.y + self.h/2)
            .frame(width: self.w, height: self.h, alignment: .center)
            .offset(CGSize(width: self.width, height: self.height))

    }
}

1 个答案:

答案 0 :(得分:1)

您正在尝试使用错误的类型(CustomView而不是Double)初始化CGFloat

您的CustomView初始化程序如下:

init(x: CGFloat, y: CGFloat, f: () -> Void)

然后使用showTragets元组值对其进行调用,即:

(id: Int, state: Bool, x: Double, y: Double)

因此,当您这样做时:

CustomView(x: item.x, y: item.y, f: {})

您正在提供Double值(用于x和y)而不是CGFloat。由于从DoubleCGFloat的转换不能隐式进行,因此您需要明确地进行以下操作:

CustomView(x: CGFloat(item.x), y: CGFloat(item.y), f: {})
相关问题