如何创建一个控制器

来源:互联网 发布:黄金价格软件下载 编辑:程序博客网 时间:2024/04/29 23:31

控制器的常见创建方式有以下几种:

1:直接创建

     MJViewController  *mj = [[MJViewController alloc] init];


2:通过storyboard创建(需要新建一个storyboard文件)

(1)先加载storyboard文件(Test是storyboard的文件名)

    UIStoryboard *storyboard = [UIStoryboard  storyboardWithName:@"Test"  bundle:nil];

(2)接着初始化storyboard中的控制器(初始化“初始控制器”,箭头所指的控制器)

   MJViewController *mj =[storyboard  instantiateInitialViewController];

(3)或者可以通过体格标识初始化对应的控制器

MJViewController *mj = [storyboard instantiateViewControllerWithIdentifier:@"two"];


3:指定xib文件来创建

MJViewController  *mj = [[MJViewController alloc]initWithNibName:@"MJViewController" bundle:nil];

(呃,这个要拖线的。最好在看下视频)---多控制器03那边。

    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];    self.window.rootViewController = [[MyViewController alloc]init];//一个窗口只能有一个根控制器    self.window.backgroundColor = [UIColor purpleColor];                /*    UITextField *txf1 = [[UITextField  alloc]init];    txf1.frame = CGRectMake(10, 10, 100, 100);    txf1.borderStyle = UITextBorderStyleRoundedRect;    [self.window addSubview:txf1];    //让窗口成为主窗口    //[self.window makeKeyWindow];    //让窗口成为主窗口,并且可见    [self.window makeKeyAndVisible];                    self.windowTwo = [[UIWindow  alloc]initWithFrame:CGRectMake(100, 100, 200, 200)];        self.windowTwo.backgroundColor = [UIColor  greenColor];    [self.windowTwo makeKeyAndVisible];                    UIButton *btn = [UIButton  buttonWithType:UIButtonTypeSystem];    [btn addTarget:self action:@selector(btnClicked) forControlEvents:UIControlEventTouchUpInside];    btn.backgroundColor = [UIColor  blackColor];    btn.frame = CGRectMake(0, 0, 20, 20);    [self.windowTwo addSubview:btn];        UITextField *txf2 = [[UITextField  alloc]init];    txf2.frame = CGRectMake(50, 50, 100, 100);    txf2.borderStyle = UITextBorderStyleRoundedRect;    [self.windowTwo addSubview:txf2];            NSLog(@"%p   %p   %p",self.window ,self.windowTwo ,[UIApplication sharedApplication].keyWindow);    NSLog(@"%@",[UIApplication sharedApplication].windows);      */            //----------第一种是alloc init    //----------第二种是storyboardwithname(利用storyboard)    //仅仅加载了storyboard文件    //UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"two" bundle:nil];    //创建storyboard灰色的控制器    //UIViewController *vc = [storyboard instantiateInitialViewController];//文件里面的控制器---箭头所指    //MyViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"pink"];//storyboard的id    //self.window.rootViewController = vc;    //NSLog(@"#############%@",vc);            //第三种创建控制器的方法(利用xib)    MyThreeViewController  *three = [[MyThreeViewController alloc]initWithNibName:@"MJThree" bundle:nil];    self.window.rootViewController = three;        [self.window  makeKeyAndVisible];    return YES;}


0 0
原创粉丝点击