属性传值

从前向后的传值方式。例如此时有A界面和B界面,我们尝试从A界面进入B界面,并将A界面的一个字符串str传到B界面。此时B界面的viewDidLoad还未加载。 我们可以将我们想传的值(例子中为str)设为B界面的属性,如下:

@interface BViewController : UIViewController

@property (nonnull, strong) NSString* str;

@end

在A界面中直接对B界面的str属性赋值

BViewController* bViewController = [[BViewController alloc] init];

bViewController.str = str;

这样就把A界面的str传到了B界面

协议传值

从后向前传值的方式。一样是上例的A,B界面,我们尝试从B界面返回A界面,并将B界面的字符串str返回到A界面。此时A界面的viewDidLoad以加载,不会再次加载。

我们在声明一个协议,再协议中声明一个方法,此方法用于传值。

@protocol RegisterViewControllerDelegate

-(void)pushString:(NSString*)str;

@end

在B类声明此协议的代理

@property id delegate;

设置A类遵守此协议,并实现协议方法

// A类遵守协议

@interface AViewController : UIViewController

@property (nonnull, strong) NSString* str;

@end

// 在A类实现方法

- (void) pushString:(NSString *)accontText {

_str = accontText;

}

在A类进入B类前设置B类代理为自己

BViewController* bViewController = [[BViewController alloc] init];

// 全屏替换A界面

bViewController.modalPresentationStyle = UIModalPresentationFullScreen;

// 设置代理

enrollViewController.delegate = self;

[self presentViewController:enrollViewController animated:YES completion:nil];

从B类返回时,调用代理传值

[self.delegate pushAccontText:str];

[self dismissViewControllerAnimated:YES completion:nil];

这样就把B界面的str返回到了A界面

相关文章

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: