IOS之UIViewController执行返回操作并传递参数值的两种方式

举个例子,第一个page(即UIViewController)显示天气,需要对所在地进行设置,这就需要跳转到第二个page,选择好所在地之后,将所在地信息(即返回参数)传回第一个page。

第一种:通过Delegate的Protocol

1.新建PassValueDelegate.h

#import <Foundation/Foundation.h>

@protocol PassValueDelegate <NSObject>

-(void)passValue:(NSString *)value;

@end

 2.在需要得到返回值的UIViewController.h添加对PassValueDelegate的实现

@interface IkrboyViewController6 : UIViewController<PassValueDelegate>

 3.在UIViewController.m实现-(void)passValue的方法,即处理得到的返回值的事件

-(void)passValue:(NSString *)value{
    NSLog(@"get backcall value=%@",value);
}

 4.在下一个UIViewController.h(即为上一个UIViewController提供返回数据)添加Delegate的参数

@property(nonatomic,assign) NSObject<PassValueDelegate> *delegate;

 5.在上一个UIViewController跳转到下一个UIViewController之前添加代码

//设置第二个窗口中的delegate为第一个窗口的self
    newViewController.delegate = self;

 6.下一个UIViewController返回到上一个UIViewController的代码

self dismissViewControllerAnimated:YES completion:^{
            //通过委托协议传值
            [self.delegate passValue:@"ululong"];
    }];

 

第二种:绑定Notification,利用userInfo参数

 1.在第一个UIViewController的viewDidLoad添加注册RegisterCompletionNotification代码

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(registerCompletion:)
                                                 name:@"RegisterCompletionNotification"
                                               object:nil];

 2.别忘了解除·Notification

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

3.实现registCompletion方法

-(void)registerCompletion:(NSNotification*)notification {
    //接受notification的userInfo,可以把参数存进此变量
    NSDictionary *theData = [notification userInfo];
    NSString *username = [theData objectForKey:@"username"];
    
    NSLog(@"username = %@",username);
}

 4.在下一个UIViewController的返回操作中添加代码

NSDictionary *dataDict = [NSDictionary dictionaryWithObject:@"MissA"
                                                         forKey:@"username"];
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"RegisterCompletionNotification"
     object:nil
     userInfo:dataDict];

    
    [self dismissViewControllerAnimated:YES completion:nil];

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值