如何刷新查看器?
这里是敏捷菜鸟。我有一个简单的应用程序,它有一个主页面,它是一个 ViewController,相关代码如下:
import SwiftUI
class GameViewController: UIViewController {
...
func updateUI() {
switch (SettingsView().selectedBGColor) {
case 0: self.view.backgroundColor = .black
case 1: self.view.backgroundColor = .red
case 2: self.view.backgroundColor = .blue
default: break
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
updateUI()
...
}
}
第二个页面是按 UI 按钮调用的“设置”页面。这个页面不是一个ViewController,只是一个View。相关代码如下:
struct SettingsView: View {
...
var bgcolors = ["Black", "Red", "Blue"]
@AppStorage("selectedBGColor") var selectedBGColor = 0
@Environment(\.dismiss) private var dismiss
var body: some View {
NavigationView {
Form {
...
Section {
Picker(selection: $selectedBGColor, label: Text("Background color")) {
ForEach(0 ..< bgcolors.count, id: \.self) {
Text(self.bgcolors[$0]).tag($0)
}
}
}
Section {
Button("Save and exit", action: {
GameViewController().updateUI()
dismiss.callAsFunction()
}).navigationBarTitle(Text("Settings"))
}
}
}
}
}
当我更改设置中选定的背景颜色并通过单击按钮关闭设置时,ViewController 的背景颜色不会更改,直到我重新启动应用程序。我如何强制它更新?我尝试了在这里找到的各种东西,例如 loadView()
、setNeedsDisplay()
、DispatchQueue
、ViewWillAppear
/ViewDidAppear
和performSegue()
但没有任何效果。帮助将不胜感激!
Swift noob here. I have a simple app that has a main page which is a ViewController, relevant code below:
import SwiftUI
class GameViewController: UIViewController {
...
func updateUI() {
switch (SettingsView().selectedBGColor) {
case 0: self.view.backgroundColor = .black
case 1: self.view.backgroundColor = .red
case 2: self.view.backgroundColor = .blue
default: break
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
updateUI()
...
}
}
And the second page is a Settings page invoked by a UIbutton press. This page is not a ViewController, just a View. Relevant code below:
struct SettingsView: View {
...
var bgcolors = ["Black", "Red", "Blue"]
@AppStorage("selectedBGColor") var selectedBGColor = 0
@Environment(\.dismiss) private var dismiss
var body: some View {
NavigationView {
Form {
...
Section {
Picker(selection: $selectedBGColor, label: Text("Background color")) {
ForEach(0 ..< bgcolors.count, id: \.self) {
Text(self.bgcolors[$0]).tag($0)
}
}
}
Section {
Button("Save and exit", action: {
GameViewController().updateUI()
dismiss.callAsFunction()
}).navigationBarTitle(Text("Settings"))
}
}
}
}
}
When I change the selected background color in the settings and close the settings by clicking the button, the background color of the ViewController doesn't change until I relaunch the app. How do I force it to update? I tried various things I found here like loadView()
, setNeedsDisplay()
, DispatchQueue
, ViewWillAppear
/ViewDidAppear
and performSegue()
but nothing worked. Help would be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论