界面使用XIB文件的几种方法

注意:提示错误“loaded the "ViewController" nib but the view outlet was not set.”时,XIB文件中view的Referencing Outlets需连到File’s Owner上。

1. AppDelegate代理中initWithNibName方法

在AppDelegate代理中

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor grayColor];
self.window.rootViewController = [[SelectHeroViewController alloc] initWithNibName:@"SelectHeroViewController" bundle:nil];

即可

2.ViewController中initWithNibName方法

在ViewController中

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view = [[[NSBundle mainBundle] loadNibNamed:@"SelectHero" owner:self options:nil] lastObject];
    }
    return self;
}

3.Identity inspector中设置

按1,AppDelegate代理中修改第3行

self.window.rootViewController = [[SelectHeroViewController alloc] initWithNibName:@"SelectHeroViewController" bundle:nil];
 改为
self.window.rootViewController = [[SelectHeroViewController alloc] init];

然后在xib文件Identity inspector中 选择控制器类

你可能感兴趣的:(界面使用XIB文件的几种方法)