创建没有笔尖的视图控制器 [英] Creating a view controller without a nib
问题描述
在AppDelegate中,我想创建一个UIViewController子类并添加它的视图。 viw本身将在代码中指定 - 没有笔尖。
In AppDelegate, I want to create a UIViewController subclass and add it's view. The viw itself will be specified in code - there is no nib.
根据苹果文档,我应该使用
Based on the apple docs, I should use
initWithNibName:nil bundle:nil];
然后在控制器的loadView中添加我的子视图等。
and then in loadView of the controller, I add my subviews etc.
但是,下面的测试代码对我不起作用。我在Apple的 PageControl演示上对AppDelegate代码进行了建模,只是因为我的应用程序将实现类似的结构(特别是一个基本控制器来管理分页滚动视图,以及一组其他控制器来构建页面)。
However, the follwing test code below does not work for me. I modelled the AppDelegate code on Apple's PageControl demo, simply because my app will implement a similar structure (specifically a base controller to manage a paged scroll view, and an array of other controller's to build the pages).
但是我怀疑我的AppDelegate代码是问题,因为日志记录证明initWithNibName ::和loadView都会触发。下面的应用程序运行,但屏幕为空白。我希望带有标签的绿色视图。
But I suspect my AppDelegate code is the problem, since logging proves that initWithNibName:: and loadView both fire. The app as below runs, but the screen is blank. I am expecting a green view with a label.
AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
ScrollerController *controller = [[ScrollerController alloc] initWithNibName:nil bundle:nil];
[self.window addSubview:controller.view];
[self.window makeKeyAndVisible];
return YES;
}
ScrollerController (UIViewController子类)
ScrollerController (the UIViewController subclass)
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)loadView{
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
UIView *contentView = [[UIView alloc] initWithFrame:applicationFrame];
contentView.backgroundColor = [UIColor greenColor];
self.view = contentView;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 40, 100, 40)];
[label setText:@"Label created in ScrollerController.loadView"];
[self.view addSubview:label];
}
推荐答案
尝试使用:
self.window.rootViewController = controller;
而不是
[self.window addSubview:controller.view];
注意,你还应该 @synthesize window;
并创建它
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
Note, that you should also @synthesize window;
and create it
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
这篇关于创建没有笔尖的视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!