多个ViewController之间传值

   多个ViewController进行传值,有三种方式:

     

            1:使用代理

            2:   使用Block

            3:使用单例

 

- (void)viewDidLoad

{

    [super viewDidLoad];

    self.navigationItem.title=@"title1";

    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"next" style:UIBarButtonItemStylePlain target:self action:@selector(next)];

    

}

-(void)next

{

    AZSecondViewController *secondVC=[[AZSecondViewController alloc] init];

    secondVC.title=@"title2";

    //第一种:使用代理 ,secondVC中见代码

    

    secondVC.delegate=self;

    

    //第二种:使用BLOCK

    

    //定义secondVC中blockFun

    secondVC.blockFun=^(NSString *title)

    {

        self.navigationItem.title=title;

    };

    

    //第三种:使用单例  -(void)viewWillAppear:(BOOL)animated

    

    [self.navigationController pushViewController:secondVC animated:YES];

}


//第三种:使用单例

-(void)viewWillAppear:(BOOL)animated

{

    AZSingleton *sington=[AZSingleton shareSingleton];

    if (sington.str==nil) {

        return;

    }

    self.navigationItem.title=sington.str;

}

//实现协议中的方法

-(void)getVaule:(NSString *)title

{

    self.navigationItem.title=title;

}


UISecondViewController:   

    //创建三个按键

    UIButton *btn1=[UIButton buttonWithType:UIButtonTypeCustom];

    btn1.frame=CGRectMake(10, 60, 300, 20);

    [btn1 setTitle:@"使用代理" forState:UIControlStateNormal];

    btn1.tag=10;

    [btn1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn1];

    

    UIButton *btn2=[UIButton buttonWithType:UIButtonTypeCustom];

    btn2.frame=CGRectMake(10, 90, 300, 20);

    btn2.tag=11;

    [btn2 setTitle:@"使用block" forState:UIControlStateNormal];

      [btn2 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn2];

    

    UIButton *btn3=[UIButton buttonWithType:UIButtonTypeCustom];

    btn3.frame=CGRectMake(10, 120, 300, 20);

    btn3.tag=12;

    [btn3 setTitle:@"使用单例" forState:UIControlStateNormal];

      [btn3 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn3];

}

-(void)btnClick:(UIButton *)btn

{

    if (btn.tag==10) {

        [self.delegate getVaule:@"使用代理"];

       

    }

    if (btn.tag==11) {

         self.blockFun(@"使用block");//定义了一个快函数,这里只是调用一下块函数,实现在rootVC中。

    }

    if (btn.tag==12) {

        AZSingleton *singleton=[AZSingleton shareSingleton];

        singleton.str=@"使用单例";

    }

}


效果:







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值