init(DelegateType .Type)
init(DelegateType .Type)
DelegateType
inherits NSObject
, DelegateType
conforms to ObservableObject
, and DelegateType
conforms to WKExtensionDelegate
.Availability 有効性
Technology
@propertyWrapper struct WKExtensionDelegateAdaptor<DelegateType> where DelegateType : NSObject
, DelegateType : WKExtensionDelegate
To handle extension delegate callbacks in an extension that uses the SwiftUI life cycle, define a type that conforms to the WKExtension
protocol, and implement the delegate methods that you need. For example, you can implement the did
method to handle remote notification registration:
class MyExtensionDelegate: NSObject, WKExtensionDelegate, ObservableObject {
func didRegisterForRemoteNotifications(withDeviceToken: Data) {
// Record the device token.
}
}
Then use the WKExtension
property wrapper inside your App
declaration to tell SwiftUI about the delegate type:
@main
struct MyApp: App {
private var extensionDelegate: MyExtensionDelegate
var body: some Scene { ... }
}
SwiftUI instantiates the delegate and calls the delegate’s methods in response to life cycle events. Define the delegate adaptor only in your App
declaration, and only once for a given extension. If you declare it more than once, SwiftUI generates a runtime error.
If your extension delegate conforms to the Observable
protocol, as in the example above, then SwiftUI puts the delegate it creates into the Environment
. You can access the delegate from any scene or view in your extension using the Environment
property wrapper:
private var extensionDelegate: MyExtensionDelegate
This enables you to use the dollar sign ($
) prefix to get a binding to published properties that you declare in the delegate. For more information, see projected
.
Important 重要
Manage an externsion’s life cycle events without using a delegate whenever possible. For example, prefer to handle changes in Scene
instead of relying on delegate callbacks, like application
.
init(DelegateType .Type)
init(DelegateType .Type)
DelegateType
inherits NSObject
, DelegateType
conforms to ObservableObject
, and DelegateType
conforms to WKExtensionDelegate
.var projectedValue : ObservedObject <DelegateType >.Wrapper
DelegateType
inherits NSObject
, DelegateType
conforms to ObservableObject
, and DelegateType
conforms to WKExtensionDelegate
.var wrappedValue : DelegateType
struct NSApplicationDelegateAdaptor
struct UIApplicationDelegateAdaptor