【发布时间】:2019-11-21 20:50:57
【问题描述】:
我有一个内部管理一个跟踪当前索引的@State 变量的视图。所以像:
struct ReusableView: View {
@State var index: Int = 0
var body: some View {
Text("The index is \(self.index)"
// A button that changes the index
}
}
此视图将在整个应用程序中重复使用。有时父视图需要访问索引,所以我这样重构它:
struct ParentView: View {
@State var index: Int = 0
var body: some View {
ReusableView($index)
}
}
struct ReusableView: View {
@Binding var index: Int
var body: some View {
Text("The index is \(self.index)"
// A button that changes the index
}
}
问题
我不想强制父视图始终保持索引的状态。换句话说,我希望有选择地允许父视图负责状态变量,但默认使用可重用视图来维护状态,以防父视图不关心索引。
尝试
我尝试以某种方式初始化可重用视图上的绑定,以防父视图不提供绑定:
struct ReusableView: View {
@Binding var index: Int
init(_ index: Binding<Int>? = nil) {
if index != nil {
self._index = index
} else {
// TODO: Parent didn't provide a binding, init myself.
// ?
}
}
var body: some View {
Text("The index is \(self.index)"
// A button that changes the index
}
}
谢谢!
【问题讨论】: