SwiftUI:递归嵌套视图



我试图创建一个视图,它是一个圆圈,在这个圆圈中应该添加更多的圆圈,直到我的递归函数结束。例如,如果我调用createSubCircle(深度:4(,我希望它本身有4个圆,其中每个子圆应该有其父圆的80%。所有圆必须具有相同的中心。

下面的代码返回

函数不透明返回类型被推断为'ZStack&lt_条件内容&lt;GeometryReader<TupleView<(一些视图,一些视图(>gt;,EmptyView>gt;',其根据自身定义不透明类型

struct ContentView: View {
var body: some View {
createSubCircle(depth: 4)
}
@ViewBuilder
func createSubCircle(depth: Int) -> some View {

ZStack {
if depth > 0 {
GeometryReader{proxy in
Circle()
.strokeBorder(.green, lineWidth: 4)
.frame(width: proxy.size.width*0.8, height: proxy.size.height*0.8, alignment: .center)
createSubCircle(depth: depth-1)
}
}
else{
EmptyView()
}
}
}

}

为什么不使用ForEach?

@ViewBuilder
func createSubCircle(depth: Int) -> some View {
ZStack {
ForEach(0..<depth, id:.self) {dep in
GeometryReader{proxy in
let width = proxy.size.width * (pow(0.8, CGFloat(dep)))
let height = proxy.size.height * (pow(0.8, CGFloat(dep)))
ZStack {
Circle()
.strokeBorder(.green, lineWidth: 4)
.frame(width: width, height: height, alignment: .center)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
}
}
}

最新更新