代理传值
要展示的控制器
- 需要准守
<ALTargetViewControllerDeleagte>
协议 - 实现
(void)text:(NSString *)text fromVC:(ALTargetViewController *)fromVC indexPath:(nonnull NSIndexPath *)indexPath
方法
@interface ALMainViewController ()<ALTargetViewControllerDeleagte>
@end
#pragma mark - ALTargetViewControllerDeleagte
- (void)text:(NSString *)text fromVC:(ALTargetViewController *)fromVC indexPath:(nonnull NSIndexPath *)indexPath
{
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
cell.detailTextLabel.text = text;
}
要反向传值的控制器
-
.h
文件需要声明协议,提供一个对外delegate
属性,只需要准守我的协议就能成为我的代理对象
@protocol ALTargetViewControllerDeleagte <NSObject>
@optional
- (void)text:(NSString *)text fromVC:(ALTargetViewController *)fromVC indexPath:(NSIndexPath *)indexPath;
@end
@interface ALTargetViewController : UIViewController
@property (nonatomic, weak)id <ALTargetViewControllerDeleagte> delegate;
@end
-
.m
文件传递展示控制器需要的内容
- (IBAction)onButton:(id)sender {
if ([self.delegate respondsToSelector:@selector(text:fromVC:indexPath:)]) {
[self.delegate text:self.textField.text fromVC:self indexPath:self.indexPath];
}
[self.navigationController popViewControllerAnimated:YES];
}
通知传值
要展示的控制器
- 添加观察者
addObserver:
- 实现通知回调传回的内容
(void)alNotification:(NSNotification *)noti
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alNotification:) name:@"ALNotification" object:nil];
}
#pragma mark - Notice
- (void)alNotification:(NSNotification *)noti {
NSDictionary *dict = noti.object;
NSString *text = dict[@"text"];
NSIndexPath *indexPath = dict[@"indexPath"];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.text = text;
}
要反向传值的控制器
- (IBAction)onButton:(id)sender {
[[NSNotificationCenter defaultCenter] postNotificationName:@"ALNotification" object:@{@"text":_textField.text, @"indexPath": self.indexPath}];
[self.navigationController popViewControllerAnimated:YES];
}