【发布时间】:2021-07-29 14:02:58
【问题描述】:
下面是我的选择器的代码:
struct pickerSwitch: View {
@ObservedObject var appState: AppState
@State var selection: String = "Red"
var colors = ["Red", "Blue"]
init(appState: AppState) {
print("Init ran again")
self.appState = appState
if appState.showBlueControl {
UISegmentedControl.appearance().setTitleTextAttributes([.font : UIFont.preferredFont(forTextStyle: .headline)], for: .normal)
UISegmentedControl.appearance().backgroundColor = .blue
} else {
UISegmentedControl.appearance().setTitleTextAttributes([.font : UIFont.preferredFont(forTextStyle: .headline)], for: .normal)
UISegmentedControl.appearance().backgroundColor = .red
}
}
var body: some View {
Picker(selection: $selection, label: Text("")) {
ForEach(colors, id: \.self) {
Text($0)
}
}.pickerStyle(SegmentedPickerStyle())
}
}
在我的代码的其他地方,我有一个按钮可以更改“AppState”特定实例的“showBlueControl”值。在我的 Xcode 日志中,我看到很多“再次运行初始化”日志,所以我认为分段控件应该发生变化,但由于某种原因,只有当我完全关闭视图并重新打开它时才会发生变化。当 SwiftUI 状态发生变化(不关闭/重新打开视图)时,如何动态更改 SegmentedControl?
【问题讨论】:
-
您在哪里更新分段更改时的 appState?
-
您可以通过
.id(selection)或.id(appState.showBlueControl)重新创建您的视图 -
附加 .id(selection) 无效,但使用 .id(appState.showBlueControl) 有效——谢谢!
-
什么是 AppState?你真的需要Minimal, Reproducible Example。
-
请记住:通过使用它,您将再次创建一个整体视图。
标签: swift xcode swiftui segmentedcontrol