我知道如何訪問場景委托:
self.view.window.windowScene.delegate
還有窗戶:
UIScene *scene = [[[[UIApplication sharedApplication] connectedScenes] allObjects] firstObject];
if ([scene.delegate conformsToProtocol:@protocol(UIWindowSceneDelegate)]) {
UIWindow *window = [(id <UIWindowSceneDelegate>)scene.delegate window];
}
但是這兩種方法都假定我沒有對 SceneDelegate.h/.m 檔案進行任何更改。
我創建了一個自定義工具列,但我不知道如何從 viewController 訪問它:
場景委托.h
#import <UIKit/UIKit.h>
@interface SceneDelegate : UIResponder <UIWindowSceneDelegate, NSToolbarDelegate>
@property (strong) NSToolbar *mainToolbar;
@property (strong, nonatomic) UIWindow * window;
@end
我使用 NSToolbar 是因為它是一個 Mac Catalyst 應用程式,也可以在 macOS 上運行。
uj5u.com熱心網友回復:
但是這兩種方法都假定我沒有對 SceneDelegate.h/.m 檔案進行任何更改。
為什么會這樣?
因為您提供的代碼回傳一個UIWindowSceneDelegate. 但是您正在尋找型別的物件SceneDelegate來訪問其介面。因此,您必須將其轉換為所需的界面。
那我該如何解決呢?
因此,您可以在任何地方訪問它,例如:
SceneDelegate.shared.myCustomProperty
通過定義一個簡單的類方法:
(SceneDelegate *)shared {
return (SceneDelegate *)UIApplication.sharedApplication.connectedScenes.allObjects.firstObject;
}
注意:不要忘記匯入屬性并將其SceneDelegate.h添加shared到其介面。
您也可以像這樣將其行內(SceneDelegate *)self.view.window.windowScene.delegate
uj5u.com熱心網友回復:
以下是檢查物件是否屬于所需類的方法:
UIScene *scene = [[[[UIApplication sharedApplication] connectedScenes] allObjects] firstObject];
if ([scene.delegate isKindOfClass:SceneDelegate.class]) {
SceneDelegate *delegate = (SceneDelegate *)scene.delegate;
NSToolbar *toolbar = delegate.mainToolbar;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477645.html
上一篇:從請求中獲取資料到主執行緒
