UIView xib创建和切换/控制器传值

来源:互联网 发布:京东算法大赛代码 编辑:程序博客网 时间:2024/06/05 09:06

    //1.创建窗口对象

    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];  

    //2.通过XIB来创建视图控制器nib(就是xib的二进制文件)

    //从[NSbundle mainbundle]主资源包中加载名称为FirstViewController的xib(nib)文件

    //方法1:

    FirstViewController *firstVC = [[FirstViewController alloc]initWithNibName:@"FirstViewController" bundle:nil];

    //方法2:

    //传nil得时候默认会去找和当前控制器名称相同的view文件

    FirstViewController *firstVC = [[FirstViewController alloc]initWithNibName:nil bundle:nil]; 

    //方法3:

    //不传任何参数的时候默认会加载方法2

    FirstViewController *firstVC = [[FirstViewController alloc]init];



  //3.将firstVC加载给跟视图控制器    

    self.window.rootViewController = firstVC;

    [self.window makeKeyAndVisible];


/**

 *  视图控制器显示的时候,首先会检查view是否存在,如果不存在,则需要加载调用loadView方法加载视图.

 *  调用loadView方法加载视图时,首先确认用户有没有重写loadView方法,如果重写了则按用户重写的来创建,如果没有重写

(1.是否有去掉Controllerxib文件,FirstView.xib文件,找到则根据这个文件view创建view.

 2.没有找到FirstView.xib,是否有当前视图控制器全名的xib文件(FirstViewController.xib),找到则根据这个XIB文件中的view来创建.

 3.如果还没有找到则创建一个空得UIView对象)

 */

- (void)loadView      //-----重写了loadView方法

{

    [super loadView];

    //自己创建view

    self.view = [[UIView alloc]init];

    self.view.backgroundColor = [UIColor grayColor];

    

}

//********************控制器视图反向传值*****************

//方法1:target_action法

firstcontroller:

   secondVC.target = self;

    secondVC.action = @selector(changeColor:);

secondcontroller:

    //添加一个属性用来保存target对象

    @property(nonatomic,strong)id target;

    //添加sel来保存action方法

    @property(nonatomic,assign)SEL action;

//判断target是否能调用action方法

    if ([(NSObject *)self.target respondsToSelector:_action]) {

        //_target对象调用_acton方法

        [(NSString *)self.target performSelector:_action withObject:[UIColor blueColor]];

    }


//方法2:通知中心监听

//1.创建通知中心观察者

    //监听通知,[NSNotificationCenter defaultCenter]系统进程的通知中心,用来监听或者发送通知

    //参数1(observer):在通知中心中注册了一个观察者,即接收通知的对象

    //参数2:观察者收到通知以后会调用的方法

    //参数3(name):通知名称(当观察者收到这个通知,会自动调用sel(参数2)指定的方法)

    //参数4:通知的发送者,如果传nil,表示任意对象发送的名为参数3指定的通知都可以,如果不为nil,表示只接收该对象发送的参数3指定的通知

    //[[NSNotificationCenter defaultCenter] addObserver:<#(id)#> selector:<#(SEL)#> name:<#(NSString *)#> object:<#(id)#>];

    [[NSNotificationCenter defaultCenteraddObserver:self selector:@selector(changeColor:) name:@"aa" object:nil];

//2.发送通知

//方法1:

    //创建通知

    //参数1:通知的名称

    //参数2:通知的发送者

    //参数3:通知相关的参数信息(颜色对象)

//收到通知后,调用[self changeColor:]并且会将"通知对象"作为changgeColor的参数

    NSNotification *not = [[NSNotification alloc]initWithName:@"changeColor" object:self userInfo:@{@"color":[UIColor brownColor]}];

    

    //发送changeColor的通知

    [[NSNotificationCenter defaultCenterpostNotification:not];

//方法2:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeColor" object:self userInfo:@{@"color":[UIColor brownColor]}];


0 0
原创粉丝点击