[英]subclassing UIWindow while using storyboards
我有與這個問題中解釋的相同的問題:
我在哪里可以將我的應用程序使用的窗口從 UIWindow 更改為我自己的帶有故事板的子類“MyWindow”?
我的問題是如何在返回“MyWindow”子類的應用程序委托中實現“window”getter 方法? 或者也許還有其他方法可以將我的子類分配給我的應用程序的主窗口?
可以按照 Apple 的UIApplicationDelegate
參考中的說明對 Storyboard 項目中的UIWindow
進行子類化:
窗戶
使用故事板時,應用程序必須通過將故事板添加到窗口並將該窗口放在屏幕上來呈現故事板。 應用程序為窗口查詢此屬性。 此屬性保留對窗口的引用是必要的,以防止窗口被釋放。 如果該屬性的值為nil
(默認值),則應用程序會創建一個UIWindow
的通用實例並將其分配給該屬性以供委托引用。 你可以實現這個協議的 getter 方法來為應用程序提供一個不同的窗口。
換句話說,在您的AppDelegate
實現中只需添加以下 getter
目標-C
- (MyCustomWindow *)window
{
static MyCustomWindow *customWindow = nil;
if (!customWindow) customWindow = [[MyCustomWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
return customWindow;
}
迅速
var customWindow: MyCustomWindow?
var window: UIWindow? {
get {
customWindow = customWindow ?? MyCustomWindow(frame: UIScreen.mainScreen().bounds)
return customWindow
}
set { }
}
你要先繼承 UIWindow 並不難
class WinCustom : UIWindow{
....
}
然后在 AppDelegate 中:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = WinCustom(frame: UIScreen.main.bounds)
self.window?.rootViewController = UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController()
return true
}
在我自己的應用程序中,我在從 Xcode 模板創建新應用程序時看到在 AppDelegate.h 中聲明了“ window
”屬性。
此時您可以修改該屬性以從“ UIWindow
”更改為“ MyWindow
”。
或者,一個不太優雅的解決方案,您可以在訪問它時簡單地將window
的返回轉換為“ MyWindow
”對象類型。
UIApplicationDelegate
協議具有您可以使用的window
屬性
import UIKit
class CustomWindow : UIWindow {
//...
}
class AppDelegate: UIResponder, UIApplicationDelegate {
var customWindow: CustomWindow?
var window: UIWindow? {
get {
customWindow = customWindow ?? CustomWindow(frame: UIScreen.main.bounds)
return customWindow
}
set { }
}
//...
}
此解決方案僅返回一個自定義 UIWindow
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.