当我们需要通过第一个界面传值给第二个界面可以通过属性传值,单例,代理,block,消息通知等方法进行传值。当我们需要从第二个界面传值到第一个界面的时候通过单例,代理,block,消息通知等方法进行传值。下面主要介绍的是第二个界面传值到第一个界面。
属性传值:
如下所示,通过模态进行两个页面之间的传值 ,首先建立两个类 A类和B类,在B类中声明一个属性:
#import <UIKit/UIKit.h>
@interface ViewControllerB :UIViewController
@property (nonatomic,copy)NSString * str;
@end
在A类包含B类头文件,在A类中获得B类属性str,进行赋值。当B类使用属性str时就可以达到传值效果。但是这样传值缺点是没有及时性,不能及时的把值传递过去。
#import <UIKit/UIKit.h>
typedefvoid (^myBlock)(NSString * str);
@interface ViewControllerB :UIViewController
@property(nonatomic,copy)myBlock block;
@end
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
ViewControllerB * tab = [[ViewControllerB alloc]init];
tab.modalTransitionStyle = 0;
tab.block=^(NSString * str){
label.text=str;
};
[selfpresentViewController:tabanimated:YEScompletion:nil];
}
-(void)backBtn
{
if (self.block) {
self.block(tf.text);
}
[selfdismissViewControllerAnimated:YEScompletion:nil];
}
@protocol viewDeletate <NSObject>
-(void)getStr:(NSString *)str;
@end
@interface ViewControllerB :UIViewController
@property (nonatomic,weak)id<viewDeletate> delegate;
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
ViewControllerB * tab = [[ViewControllerB alloc]init];
tab.modalTransitionStyle = 0;
tab.delegate =self;
[selfpresentViewController:tabanimated:YEScompletion:nil];
}
实现代理方法:
-(void)getStr:(NSString *)str{
label.text = str;
NSLog(@"%@",str);
}