swift - 发生状态更改时 UISegmentedControl 不更改
问题描述
下面我有我的选择器的代码:
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?
解决方案
您只需要@State
跟踪背景颜色。然后你.background()
在选择器上设置。要更改您的状态变量,只需使用.onChange
.
struct PickerSwitch: View {
@State var selection: String = "Red"
var colors = ["Red", "Blue"]
@State var backgroundColor = Color.red // This tracks your background color
var body: some View {
Picker(selection: $selection, label: Text("")) {
ForEach(colors, id: \.self) {
Text($0)
}
}
// .onChange reacts to the change of selection
.onChange(of: selection, perform: { value in
if value == "Red" {
backgroundColor = .red
} else {
backgroundColor = .blue
}
})
.pickerStyle(SegmentedPickerStyle())
.background(backgroundColor) // Set your background color here
}
}
推荐阅读
- c# - 有没有办法检查 RouteConfig.cs 文件中的浏览器名称?
- javascript - stylePreprocessorOptions 角度 8
- sql - Segregate the row based on the date time column per each month
- android - 用于反应原生的原生 android 后台模块
- node.js - Graphql 仅在传递参数时执行 where 条件
- javascript - 逗号十进制值的vue指令绑定值问题
- c++ - 类与朋友而不是前向声明,:哪个编译器是正确的
- javascript - Nestjs:将提供者注入到由关键字 new 创建的对象中
- python - 将 django 部署到 Heroku 时出现服务器错误 500
- vue.js - 有没有办法从多个选择中获取数据作为数组?