[英]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.