[英]Creating a view controller without a nib
在AppDelegate中,我想创建一个UIViewController子类并添加它的视图。 viw本身将在代码中指定 - 没有笔尖。
根据苹果文档,我应该使用
initWithNibName:nil bundle:nil];
然后在控制器的loadView中,我添加我的子视图等。
但是,下面的后续测试代码对我不起作用。 我在Apple的PageControl演示中对AppDelegate代码进行了建模,仅仅因为我的应用程序将实现类似的结构(特别是用于管理分页滚动视图的基本控制器,以及用于构建页面的其他控制器阵列)。
但我怀疑我的AppDelegate代码是问题,因为日志记录证明initWithNibName ::和loadView都会触发。 下面的应用程序运行,但屏幕为空白。 我期待带有标签的绿色视图。
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子类)
- (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];
而不是initWithNibNamed:,只需使用alloc和init或任何其他指定的initalizer用于视图控制器。 这是一个项目的例子
hoverViewController=[[BDHoverViewController alloc] initWithHoverStatusStyle:BDHoverViewStatusActivityProgressStyle];
self.window.rootViewController=hoverViewController;
[self.window makeKeyAndVisible];
另外,将根视图控制器添加到app delegate中的窗口的正确形式(现在无论如何)如下所示:
self.window.rootViewcontroller=controller;
[self.window makeKeyAndVisible];
您无需将视图添加到窗口。 上面的代码自动完成。
祝好运,
Ť
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.