创建没有笔尖的视图控制器

Ben*_*ard 4 model-view-controller uiviewcontroller uiview ios ios5

在AppDelegate中,我想创建一个UIViewController子类并添加它的视图.viw本身将在代码中指定 - 没有笔尖.

根据苹果文档,我应该使用

initWithNibName:nil bundle:nil];
Run Code Online (Sandbox Code Playgroud)

然后在控制器的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;
    }
Run Code Online (Sandbox Code Playgroud)

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];
}
Run Code Online (Sandbox Code Playgroud)

Sul*_*han 5

尝试使用: self.window.rootViewController = controller; 而不是 [self.window addSubview:controller.view];

请注意,您还应该@synthesize window;创建它 self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];