I'm writing a "blackbox" library. In this library I need to add a subView to any app which uses my library.
Therefore, I don't have any reference to the appDelegate nor to the UIWindow of the application. The only thing the external app is doing now is the following :myRec = [[Rec alloc] init];
myRec.delegate = self;
[myRec start];
where Rec is the blackbox library and myRec is the instance that's used by an external app.
Of course, I can't get any reference to the view of the app through the delegate member cause it's not defined like the specific type of the external app. Any ideas on how to get a grasp on the UIWindow object / appDelegate object without knowing their identity in advance ?? T开发者_运维百科hanks !!Getting the App Delegate:
id<UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate];
Getting the UIWindow object:
UIWindow* window = [[UIApplication sharedApplication] keyWindow];
[[UIApplication sharedApplication] delegate]
Will always returns something conform to id<UIApplicationDelegate>
Btw, this is the proper way of doing it, create a protocol that some class in your application is supposed to conform to (i.e. the appDelegate) and pass that class to your library. You library can check that the class is well conform to the protocol and fail with a message in the log if not.
@phix23 his answer in Swift 3:
if let appDelegate = UIApplication.shared.delegate, let window = appDelegate.window {
let yourview = window?.rootViewController?.view
}
精彩评论