[英]How to access main window from view controllers in Objective-C?
I create a custom view controller named HomeViewController
which inherits from UIViewController
. 我创建了一个名为
HomeViewController
的自定义视图控制器,它继承自UIViewController
。 In main application delegate, I show it by calling [window addSubview:homeViewController.view]
inside function applicationDidFinishLaunching
. 在主应用程序委托中,我通过在函数
applicationDidFinishLaunching
调用[window addSubview:homeViewController.view]
显示它。 Yeah, everything works fine. 是的,一切正常。
Now I add a button into the HomeViewController
xib file. 现在我在
HomeViewController
xib文件中添加一个按钮。 When I click on it, I want the window
to remove the current view and add another navigationController
instead. 当我点击它时,我希望
window
删除当前视图并添加另一个navigationController
。 I make a function inside HomeViewController.m
and link to the button but I don't know how to access the property window
from there. 我在
HomeViewController.m
创建一个函数并链接到按钮,但我不知道如何从那里访问属性window
。 window
is a local variable inside the main app delegate and button click handler is inside HomeViewController
. window
是主应用程序委托中的局部变量,按钮单击处理程序位于HomeViewController
。 I'm thinking of doing the similar thing as above which is to add navigationController.view
as subview of window
. 我正在考虑做与上面类似的事情,即添加
navigationController.view
作为window
子视图。
Sorry! 抱歉! I'm very new to this iphone app development.
我对这个iphone应用程序开发很新。 I don't really get the big picture of how the application flow should be.
我并没有真正了解应用程序流程应该如何。 Perhaps something's wrong with the structure of my project?
也许我的项目结构出了问题?
您可以使用以下行访问应用中任何位置的主窗口
[[[UIApplication sharedApplication] windows] objectAtIndex:0]
[(AppDelegate *)[[UIApplication sharedApplication] delegate] window]
might help you to access window
property of a delegate. [(AppDelegate *)[[UIApplication sharedApplication] delegate] window]
可能会帮助您访问委托的window
属性。
AppDelegate
is your delegate class name. AppDelegate
是您的委托类名称。
You can add an extension to UIViewController. 您可以向UIViewController添加扩展。 In Swift:
在Swift中:
extension UIViewController {
var window : UIWindow {
return UIApplication.shared.windows.first!
}
}
Now you can access it from within any view controller. 现在,您可以从任何视图控制器中访问它。 For example:
例如:
override func viewDidLoad() {
super.viewDidLoad()
self.window.tintColor = .orange
}
Ostensibly you should have a window, so you should be able to safely force unwrap the window, however, you can just make it optional if you are doing something different with your window hierarchy: 表面上你应该有一个窗口,所以你应该能够安全地强行打开窗口,但是,如果你正在做与窗口层次结构不同的事情,你可以选择它:
extension UIViewController {
var window : UIWindow? {
return UIApplication.shared.windows.first
}
}
Implementation using optionals: 使用期权的实施:
override func viewDidLoad() {
super.viewDidLoad()
if let window = self.window {
window.tintColor = .orange
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.