[英]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.