iOS ViewController间传值

delegate方式和block方式

解决方案一:delegate方式

从当前页面传值给上一个页面,使用delegate

回传值

第一个页面:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//获取跳转的ViewController
    SecondViewController* vc = segue.destinationViewController;
    vc.delegate = self;
}

//实现协议方法
-(void)userDidEnterName:(NSString *)info{
    self.nameLabel.text = info;
}

第二个页面:
.h文件

@protocol DataEnterDelegate
-(void)userDidEnterName:(NSString* )info;
@end

@interface SecondViewController : UIViewController
@property (nonatomic) id  delegate;
@end

.m文件

//点击按钮返回前一个页面
- (IBAction)okBtPressed:(id)sender {
    [_delegate userDidEnterName:self.nameTxt.text];
    [self.navigationController popViewControllerAnimated:YES];
}

解决方案二:block方式

第一个页面:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    SecondViewController* vc = segue.destinationViewController;
 
//给后一个页面的成员变量block赋值   
    vc.returnValueBlock = ^(NSString* text){
        self.nameLabel.text = text;
    };
    
}

第二个页面:
.h文件

typedef void(^returnValueBlock)(NSString* text);
@interface SecondViewController : UIViewController
@property(nonatomic) returnValueBlock returnValueBlock;

-(void)returnValue:(returnValueBlock)block;
@end

.m文件

//set block
-(void)returnValue:(returnValueBlock)block{
    self.returnValueBlock = block;
}

- (IBAction)blockBtPressed:(id)sender {
    if (self.returnValueBlock != nil) {
        self.returnValueBlock(self.nameTxt.text);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

iOS新手上路,多多指教……(_)

你可能感兴趣的:(iOS ViewController间传值)