gpt4 book ai didi

swiftui - 无法将 SwiftUI.ExtensionDelegate 转换为 ExtensionDelegate

转载 作者:行者123 更新时间:2023-12-04 00:54:02 27 4
gpt4 key购买 nike

使用 SwiftUI 架构 WatchOS 应用程序,如果你想使用 ExtensionDelegate,你需要创建你自己的。我已经这样做了,但是当我尝试实际访问代码中的委托(delegate)时,我收到以下错误消息无法转换类型的值 SwiftUI.ExtensionDelegate' (0x7fff8441b480) to 'TestMe_WatchKit_Extension.ExtensionDelegate' (0x10c3b36d0).我已将 ExtensionDelegate 定义为 -

class ExtensionDelegate: NSObject, WKExtensionDelegate {
var meetingStatistics: MeetingStatistics = MeetingStatistics()
override init(){
super.init()
}
func applicationDidFinishLaunching() {
// Perform any final initialization of your application.
print("applicationDidFinishLaunching for watchOS")
}
func applicationDidBecomeActive() {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillResignActive() {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, etc.
}
}
在我的@main - 我有以下内容:
@main
struct WatchApp: App {
@WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate
// code

}
当我尝试访问代表时 - let delegate = WKExtension.shared().delegate as! ExtensionDelegate我收到上述错误。

最佳答案

WKExtension.shared().delegate不是您的 ExtensionDelegate 而是 内部 SwiftUI.ExtensionDelegate (如前所述),它提供了您的适配器 代表 .您必须使用(到处传递)为您的 via 提供的适配器委托(delegate)的唯一实例

@WKExtensionDelegateAdaptor(ExtensionDelegate.self) var delegate
更新:
使用您的 delegate您必须将其作为参数传递给 View ,例如作为环境(因此您可以在任何 subview 中将其用作 @Environment(\.appDelegate) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.appDelegate, delegate)
}
}
struct DelegateKey: EnvironmentKey {
typealias Value = ExtensionDelegate?
static let defaultValue: ExtensionDelegate? = nil
}

extension EnvironmentValues {
var appDelegate: DelegateKey.Value {
get {
return self[DelegateKey.self]
}
set {
self[DelegateKey.self] = newValue
}
}
}

关于swiftui - 无法将 SwiftUI.ExtensionDelegate 转换为 ExtensionDelegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64082376/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com