subclassing UIWindow while using storyboards

a 夏天 提交于 2019-11-27 09:01:21

UIWindow in a Storyboard project can be subclassed as explained in Apple's UIApplicationDelegate reference:

window
When a storyboard is being used, the application must present the storyboard by adding it to a window and putting that window on-screen. The application queries this property for the window. The retained reference to the window by this property is necessary to keep the window from being released. If the value of the property is nil (the default), the application creates a generic instance of UIWindow and assign it to this property for the delegate to reference. You may implement the getter method of this protocol to provide the application with a different window.

In other words in your AppDelegate implementation simply add the following getter

Objective-C

- (MyCustomWindow *)window
{    
    static MyCustomWindow *customWindow = nil;
    if (!customWindow) customWindow = [[MyCustomWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    return customWindow;
}

Swift

var customWindow: MyCustomWindow?    
var window: UIWindow? {
    get {
        customWindow = customWindow ?? MyCustomWindow(frame: UIScreen.mainScreen().bounds)
        return customWindow
    }
    set { }
}

In my own apps, I've seen "window" property declared in AppDelegate.h when creating a new app from the Xcode templates.

You can modify that property to change from "UIWindow" to "MyWindow" at that point.

Or, a less elegant solution, you can simply cast window's return to a "MyWindow" object type when accessing it.

Its not so hard you're going to first subclass UIWindow

class WinCustom : UIWindow{ 
....
}

then in 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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!