详解iOS页面传值(顺传 逆传)

2020-01-18 19:49:01于海丽

代理协议传值

顺传

假设A为第一个视图控制器,B为第二个视图控制器

在A中导入B的.h文件

场景:A向B传值

第一步:在B的.h中定义一个content属性


@interface SecondViewController : UIViewController
@property(nonatomic,copy)NSString *contents;
@end

第二步:在点击A中的按钮方法里面给B的content属性赋值


- (void)buttonAction:(UIButton *)button
 {
 NSLog(@"进入第二页");
 SecondViewController *secondVC = [SecondViewController alloc] init];
 secondVC.contents = self.label.text;
 [self.navigationController pushViewController:secondVC animated:YES];
 }

第三部:在B使用content的属性给相应的控件赋值


@implemention SecondViewController
- (void)viewDidLoad {
 [super viewDidLoad];
 self.view.backgroundColor = [UIColor whiteColor];
 self.navigationItem.title = self.contents;
 }

逆传

代理传值使用在两个界面传值的之后,从后向前传值。

假设A为第一个视图控制器,B为第二个视图控制器

场景:B向A传值

第一步:首先在B的.h文件中声明协议和协议方法

第二步:在B的.h中声明一个代理属性,这里主要注意用assign或weak修饰,weak和assign是一种非拥有关系的指针,通过这两种修饰符修饰的指针变量,都不会改变被引用的对象的引用计数。但是在一个对象被释放后,weak会自动将指针指向nil,而assign则不会。所以,用weak更安全些。

@property (nonatomic,weak)id<协议名>delegate;


#pragma mark 这里是B的.h
#import<UIKit/UIKit.h>
@protocol CsutomTabBarDelegate<NSObject>
// 把btn的tag传出去的方法
- (void)selectedIndexWithTag:(NSInteger)tag;
@end
@interface CustomTabBarView : UIView
//声明一个代理属性delegate
@property (nonatomic,weak)id<CsutomTabBarDelegate>delegate;
@end

第三部:在B即将POP回前一个界面的时候,在pop方法的上一行使用协议方法传递数据[self.delegate 协议方法名:(参数,也就是要传回的数据)


#pragma mark 这里是B的.m
// 判断在制定的代理类中是否实现了该协议方法
// 确保执行时无此方法时不崩溃
if([self.delegate respondsToSelector:@selector(selectedIndexWithTag:)])
{
 // 执行代理方法
 [self.delegate selectedIndexWithTag:(sender.tag - 1000)];
}
else
{
 NSLog(@"协议中的方法没有实现");
}

在A的.m中,在push到B界面方法之前,B对象的初始化之后,指定A对象为B对象的代理(B对象).delegate = self此时会有黄色警告,因为没有准守协议


#pragma mark A的.m中
// 指定代理,B就是customView
customView .delegate = self;