【发布时间】:2020-04-08 21:59:44
【问题描述】:
是否可以通过编程方式动态地将多个 SwiftUI 视图添加到父视图?
例如假设我们有一个基本视图,例如:
struct MyRectView: View {
var body: some View {
Rectangle()
.fill(Color.red)
.frame(width: 200, height: 200)
}
}
还有一个Button定义为:
struct MyButtonThatMakesRects: View {
var body: some View {
Button(
action: {
// Create & add Views to parent here?
// ...
},
label: {
Text("tap to create a Rect")
}
)
}
}
当MyButtonThatMakesRects 被点击时,有什么方法可以在父视图中创建MyRectView 的多个实例?
我最初的想法与我在 UIKit 中的做法是一致的。在点击按钮时,创建一个新的UIView(),然后使用.addSubview(...) 将其添加到父级。不确定 SwiftUI 是否有类似的功能。或者也许有一种我没有看到的更简单的方法?
【问题讨论】: