在Objective-C中如何获取窗口。

huangapple go评论86阅读模式
英文:

SwiftUI: How to get window in Objective-C

问题

Here's the Objective-C code for the provided Swift code snippet:

UIScene *scene = [[[[UIApplication sharedApplication] connectedScenes] allObjects] firstObject];
if ([scene.delegate isKindOfClass:[UIWindowSceneDelegate class]]) {
    UIWindowScene *windowScene = (UIWindowScene *)scene;
    UIWindow *window = windowScene.windows.firstObject;
}

This code converts the Swift code to Objective-C and handles the differences in scene delegation between the two languages.

英文:
let scene = UIApplication.shared.connectedScenes.first
if let sd: SceneDelegate = (scene?.delegate as? SceneDelegate) {
    let window = sd.window
}

this is in Swift, I want to convert this into Objective-C. I have tried this:

UIScene *scene = [[[[UIApplication sharedApplication]connectedScenes]allObjects]firstObject];

but now there is no SceneDelegate; in Objective-C there is UIKit's UIWindowSceneDelegate.

also I wasn't able to access UIScenedelegate. Scenedelegate is in Swift and I am trying to get window in objective-c
but now I'm not able to access window in swiftUI.

答案1

得分: 5

检查 scene.delegate 以确保它符合协议,然后将协议强制转换为它,这样编译器将允许您使用协议的属性和/或方法。

UIScene *scene = [[[[UIApplication sharedApplication] connectedScenes] allObjects] firstObject];

if([scene.delegate conformsToProtocol:@protocol(UIWindowSceneDelegate)]){
    UIWindow *window = [(id <UIWindowSceneDelegate>)scene.delegate window];
}
英文:

Check scene.delegate to make sure it conforms to the protocol, then cast the protocol on it so the compiler will let you use the protocol properties and/or methods.

UIScene *scene = [[[[UIApplication sharedApplication] connectedScenes] allObjects] firstObject];

if([scene.delegate conformsToProtocol:@protocol(UIWindowSceneDelegate)]){
    UIWindow *window = [(id &lt;UIWindowSceneDelegate&gt;)scene.delegate window];
}

huangapple
  • 本文由 发表于 2020年1月6日 22:04:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定