为什么在AppDelegate中更新@State不起作用?

时间:2020-07-20 10:41:42

标签: swiftui

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视图内工作吗?

1 个答案:

答案 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