iOS載入控制器的三種方式/loadNibName與initwithNibName的區別
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
#pragma mark - 通過xib建立控制器
/**
1.在建立控制器的時候直接指定要載入xib作為控制器的view,名稱不相干
> 需要修改xib檔案的fileOwner
> 需要將fileOwner裡面的view指向xib裡面的view
2.xib檔案的名稱跟控制器相似,但是不同名
3.xib
*/
// 1.建立視窗
// brightness 可以調節螢幕亮度
self.window = [[UIWindowalloc]initWithFrame:[UIScreenmainScreen].bounds];
// 2.設定視窗的根控制器
// CZXibController *xibVc = [[CZXibController alloc] initWithNibName:@"CZMmd" bundle:nil];
// 載入相似名稱的xib
// CZXibController *xibVc = [[CZXibController alloc] init];
// 載入名稱相同的xib
// UIView *v = [[[NSBundle mainBundle] loadNibNamed:@"CZMmd" owner:nil options:nil] lastObject];
CZXibController *xibVc = [[CZXibControlleralloc]init];
self.window.rootViewController = xibVc;
// 3.讓視窗做為主視窗並且可見
[self.windowmakeKeyAndVisible];
returnYES;
}
#pragma mark -
- (void)storyboard {
// 1.建立視窗
self.window = [[UIWindowalloc]initWithFrame:[UIScreenmainScreen].bounds];
// 2.設定根控制器
// 1.先載入sb檔案
UIStoryboard *czsb = [UIStoryboardstoryboardWithName:@"CZSb"bundle:nil];
// instant 例項化
// UIViewController *sbVc = [czsb instantiateInitialViewController];
// UITableViewController *tableVc = [czsb instantiateViewControllerWithIdentifier:@"table"];
// self.window.rootViewController = tableVc;
// "command + ]" 向右邊縮排
// "command + option + ]" 向下移動
UIViewController *sbVc = [czsbinstantiateViewControllerWithIdentifier:@"sb"];
self.window.rootViewController = sbVc;
// int c;
// int a = 10;
//
// int b = 20;
//
// c = a;
// c = b;
// 3.作為主視窗並可見
[self.windowmakeKeyAndVisible];
}
#pragma mark - 通過程式碼的方式建立 alloc + init
- (void)code {
// 1.建立視窗
self.window = [[UIWindowalloc]initWithFrame:[UIScreenmainScreen].bounds];
// 2.設定視窗的根控制器
// 通過純程式碼的方式建立
CZCodeController *codeVc = [[CZCodeControlleralloc]init];
self.window.rootViewController = codeVc;
// 3.設定為主視窗並顯示
[self.windowmakeKeyWindow];
self.window.hidden =NO;
}
=======initWithNibName和loadNibName的區別---建立控制器
注意事項: --------xib建立的View:------
-(instancetype)initWithFrame:(CGRect)frame{
if(self==[superinitWithFrame:frame]){
self=[[[NSBundlemainBundle] loadNibNamed:@"LYHomeGuanggaoTJVC"owner:selfoptions:nil] lastObject];
self.frame=frame;//這個必須要設定,根據不同平臺設定View的大小;
}
returnself;
}
- (void)awakeFromNib
{
[superawakeFromNib];
[selfinitView];
}
--------在另外一個控制器中使用xib建立的View---根據不同螢幕設定大小LYHomeGuanggaoTJVC *guanggao;
if(WIDTH==320){
guanggao= [[LYHomeGuanggaoTJVC alloc]initWithFrame:CGRectMake(0, 0, 320, HEIGHT)];
}elseif(WIDTH==375){
guanggao= [[LYHomeGuanggaoTJVC alloc]initWithFrame:CGRectMake(0, 0, 375, HEIGHT)];
}elseif(WIDTH==414){
guanggao= [[LYHomeGuanggaoTJVC alloc]initWithFrame:CGRectMake(0, 0,414, HEIGHT)];
}
self.guanggao=guanggao;
[self.contentView addSubview:guanggao];