如何解决SwiftUI 2中的选择器onChange不会更改UINavigationBar.appearance
这是一个很奇怪的...在启动SwiftUI 2之前,我在视图的init()中设置UINavigationBar.appearance()如下:
init(selectedStyle: Binding<Int>) {
_selectedStyle = selectedStyle
if self.selectedStyle == 1 {
UINavigationBar.appearance().backgroundColor = UIColor.init(displayP3Red: 7/255,green: 7/255,blue: 7/255,alpha: 1)
UISegmentedControl.appearance().backgroundColor = .black
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black],for: UIControl.State.selected)
UISegmentedControl.appearance().selectedSegmentTintColor = .white
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white],for: UIControl.State.normal)
} else {
UINavigationBar.appearance().backgroundColor = .white
UISegmentedControl.appearance().backgroundColor = .white
UISegmentedControl.appearance().selectedSegmentTintColor = .white
UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black],for: UIControl.State.selected)
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black],for: UIControl.State.normal)
}
}
在SwiftUI 1中,视图将再次初始化,因此导航栏的新外观将正确更新。因为init()函数将再次运行。我试图将相同的代码放入附加到Picker的onChange()内,但由于某种原因它不起作用:
Picker(selection: $selectedStyle,label: Text("")) {
ForEach(0 ..< 3) {
Text([$0])
}
}
.pickerStyle(SegmentedPickerStyle())
.onChange(of: selectedStyle,perform: { change in
if self.selectedStyle == 1 {
UINavigationBar.appearance().backgroundColor = UIColor.init(displayP3Red: 7/255,for: UIControl.State.normal)
}
})
解决方法
appearance
对UI元素有效,在设置了相应外观后 创建。因此,您需要重新创建所有依赖的UI。
可能的方法如下-假设您在NavigationView
的根目录中有ContentView
,可以通过以下方式重新创建它(以及所有子视图)
var body: some View {
NavigationView {
// .. content here
}.id(selectedStyle) // << here !!
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。