import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@State var isFocused: Bool = true
var window: NSWindow!
// Some window setup code here
func applicationDidBecomeActive(_ notification: Notification) {
isFocused = true
}
func applicationDidResignActive(_ notification: Notification) {
isFocused = false
}
}
我尝试打印isFocused
值,即使在true
语句后立即也总是isFocused = false
。 @State
仅在SwiftUI
视图内工作吗?
答案 0 :(得分:1)
文档:
/// A linked View property that instantiates a persistent state /// value of type `Value`, allowing the view to read and update its /// value. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) @frozen @propertyWrapper public struct State<Value> : DynamicProperty {
因此,State
用于SwiftUI View
,但是AppDelegate
不是View
。