SwiftUI ForEach类型'_';没有成员';id';
当我在SwiftUI ForEach类型'_';没有成员';id';,swiftui,Swiftui,当我在ForEach中使用自定义视图时,我得到的类型“\u”没有成员“id”错误。当我使用文本(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:
ForEach
中使用自定义视图时,我得到的类型“\u”没有成员“id”错误。当我使用文本(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)
]
自定义视图:
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))
}
}
您试图用错误的类型(
Double
而不是CGFloat
)初始化CustomView
)
您的CustomView
初始值设定项如下所示:
init(x:CGFloat,y:CGFloat,f:()->Void)
使用showTargets
元组值调用它,即:
(id:Int,state:Bool,x:Double,y:Double)
所以当你这样做的时候:
CustomView(x:item.x,y:item.y,f:{})
您提供的是Double
值(用于x和y),而不是CGFloat
。由于从Double
到CGFloat
的转换不能是隐式的,因此您需要显式执行:
CustomView(x:CGFloat(item.x),y:CGFloat(item.y),f:{})
修复了,谢谢!非常隐晦的错误消息和顺便说一句。在其他情况下,我不需要“强制转换”到CGFloatSuper帮助!非常感谢。
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))
}
}