-(void)viewLoad的几种猜测

本文详细解释了iOS应用中视图的创建方式,包括无XIB文件创建和有XIB文件创建两种情况,并阐述了如何通过XIB文件实现视图的复用与配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

没有xib文件创建

- (void)viewLoad {
    //1 view为空(没有xib文件)
    //2 调用view的get方法时
    //get方法推测
//    -(UIView *)view {
//        if (_view == nil) {
//            [self viewLoad];
//            [self viewDidLoad];
//        }
//    }
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = view;
  }  

有xib文件时创建

-(void)viewLoad {
    //获取xib路径
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"RootViewController" ofType:@"nib"];
    if (filePath) {
        //有,拿出放到数组再取出
        NSArray *array = [[NSBundle mainBundle]loadNibNamed:@"RootViewController" owner:nil options:nil];
        self.view = [array lastObject];
    }else{
        //没有就创建一个view
        UIView *view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        self.view = view;
    }
}

有其他xib文件时创建

先把view.xib文件与ViewController类连接

#import "AppDelegate.h"
#import "ViewController.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    //window的创建
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    //设置window的颜色
    self.window.backgroundColor = [UIColor whiteColor];
    //设置self.window为keyWindows并显示
    [self.window makeKeyAndVisible];

    ViewController *viewController = [[ViewController alloc]initWithNibName:@"View" bundle:[NSBundle mainBundle]];

    self.window.rootViewController = viewController;
    return YES;
}

@end
#import "ViewController.h"
#import "ViewController.h"

@implementation ViewController

-(void)viewLoad {
    //获取xib文件名字
    NSString *fileName = self.nibName ? self.nibName : @"ViewController";
    //获取xib文件资源包
    NSBundle *bundle = self.nibBundle ? self.nibBundle : [NSBundle mainBundle];
    //获取xib文件路径
    NSString *filePath = [bundle pathForResource:fileName ofType:@"nib"];

    if (filePath) {
        //若有,就取出
        NSArray *array = [bundle loadNibNamed:fileName owner:nil options:nil];
        self.view = [array lastObject];
    }else{
        //没有就创建一个view
        UIView *view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        //view.backgroundColor = [UIColor orangeColor];
        self.view = view;
    }
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值