【发布时间】:2020-10-11 05:07:00
【问题描述】:
我正在使用弹出框编写 MacOS (10.15 Catalina) 应用程序。主 ContentView 包含一个带有简单切换的自定义视图:
class AppDelegate: NSObject, NSApplicationDelegate {
var popover=NSPopover()
func applicationDidFinishLaunching(_ aNotification: Notification) {
self.popover.contentViewController = NSHostingController(rootView: contentView)
self.statusBarItem = NSStatusBar.system.statusItem(withLength: 18)
if let statusBarButton = self.statusBarItem.button {
statusBarButton.title = "☰"
statusBarButton.action = #selector(togglePopover(_:))
}
func show() {
let statusBarButton=self.statusBarItem.button!
self.popover.show(relativeTo: statusBarButton.bounds, of: statusBarButton, preferredEdge: NSRectEdge.maxY)
}
func hide() {
popover.performClose(nil)
}
@objc func togglePopover(_ sender: AnyObject?) {
self.popover.isShown ? hide() : show()
}
}
struct ContentView: View {
var body: some View {
Test("Hello")
// more stuff
}
}
struct Test: View {
var message: String
@State private var clicked: Bool = false
init(message: String) {
self.message = message
_clicked = State(initialValue: false)
print("init")
}
var body: some View {
return HStack {
Text(message)
Button("Click") {
self.clicked = true
}
if !self.clicked {
Text("Before")
}
else {
Text("After")
}
}
}
}
每当弹出窗口再次出现时,我想在自定义视图中重新初始化一些数据。因此,在本例中,clicked 应重置为 false。我已经尝试了@Binding 和@State 变量的所有组合,我可以在许多搜索中找到,但似乎没有任何效果。 .onAppear() 似乎只在第一次触发。
init() 函数之所以存在,是因为在我的应用程序中我还需要包含其他内容和代码。在此示例中,我尝试使用它来初始化 clicked 状态变量,但是,虽然 print() 函数确实打印,但变量似乎没有被重置。
如何重新初始化@State 变量?
【问题讨论】: