如何在 forEach 循环中传递变量函数 [英] How to pass variables functions in forEach loops
问题描述
我目前正在编写一些代码来创建一个六边形网格,每个六边形都用渐变着色.但是,我对 swiftUI 还是很陌生,不完全理解为什么我的代码不起作用.
I am currently working on some code to create a grid of hexagons, each one individually coloured with a gradient. However I am quite new to swiftUI and don't fully understand why my code doesn't work.
ForEach(0 ..< 11, id: \.self) { Xnum in
ForEach(0 ..< 11, id: \.self) { Ynum in
self.MyNewPath(in: CGRect(), Xcoord: Double(Xnum), Ycoord: Double(Ynum), Type: 1)
.fill(RadialGradient(
gradient: Gradient(colors: [Color.red, Color.blue]),
center: .init(
x: self.gradientParametersX(Xpos: Double(Xnum)),
y: self.gradientParametersY(Ypos: Double(Ynum), Xpos: Double(Xnum))),
startRadius: CGFloat(2.0),
endRadius: CGFloat(70.0)))
.gesture(
TapGesture().onEnded {_ in
self.dataEditor(Xplace: Int(Xnum), Yplace: Int(Ynum))
}
)
}
}
返回类型:
MyNewPath()
-Path
(六边形)gradientParametersY()
-CGFloat
gradientParametersY()
-CGFloat
MyNewPath()
-Path
(of a hexagon)gradientParametersY()
-CGFloat
gradientParametersY()
-CGFloat
Return Types:
编译器无法在合理的时间内对该表达式进行类型检查;尝试将表达式分解为不同的子表达式
错误似乎集中在将 Xnum
和 Ynum
传递给函数 gradientParametersX()
和 gradientParametersY()代码>.
The error appears to be centred around the passing of Xnum
and Ynum
to functions gradientParametersX()
and gradientParametersY()
.
例如当我通过 7.0 和 0.0 时:
When I pass 7.0 and 0.0 for example:
x: self.gradientParametersX(Xpos: Double(7.0)),
y: self.gradientParametersY(Ypos: Double(0.0), Xpos: Double(7.0))),
...没有错误.
推荐答案
尝试在单独的函数中单独创建网格项,如下所示(代码快照不可测试,所以只是简单地演示想法)
Try to separate grid item creation in separate function as below (the code snapshot is not testable, so just scratchy to demo idea)
...
ForEach(0 ..< 11, id: \.self) { Xnum in
ForEach(0 ..< 11, id: \.self) { Ynum in
self.createItem(for: Xnum, Ynum: Ynum)
}
}
...
private func createItem(for Xnum: Int, Ynum: Int) -> some View {
self.MyNewPath(in: CGRect(), Xcoord: Double(Xnum), Ycoord: Double(Ynum), Type: 1)
.fill(RadialGradient(
gradient: Gradient(colors: [Color.red, Color.blue]),
center: .init(
x: self.gradientParametersX(Xpos: Double(Xnum)),
y: self.gradientParametersY(Ypos: Double(Ynum), Xpos: Double(Xnum))),
startRadius: CGFloat(2.0),
endRadius: CGFloat(70.0)))
.gesture(
TapGesture().onEnded {_ in
self.dataEditor(Xplace: Int(Xnum), Yplace: Int(Ynum))
}
)
}
这篇关于如何在 forEach 循环中传递变量函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!