在开发的过程中,经常会用到传值,上级页面向下一级页面传值,这个就不多说了,很简单的,正向传值就好了。重点说下,二级页面向上级页面传值,这里以点击tableView上的cell为例
1. 创建model, 添加几个属性
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *address;
@property (nonatomic, copy) NSString *telPhone;
2. 代理传值--在cell里面,添加model这个属性,同时,定义一个协议,声明代理方法,定义代理
#import <UIKit/UIKit.h>
#import "MCModel.h"
// 点击cell 把 model 传过去,利用 代理 传值
@protocol MCTableViewCellDelegate <NSObject>
- (void)receiveModel:(MCModel *)model;
@end
@interface MCTableViewCell : UITableViewCell
@property (nonatomic, strong)MCModel *model;
@property (nonatomic, weak) id <MCTableViewCellDelegate> delegate; // 声明代理
@end
在cell上的按钮触发事件
- (IBAction)clickBtnAction:(UIButton *)sender {
if ([self.delegate respondsToSelector:@selector(receiveModel:)]) {
[self.delegate receiveModel:self.model];
}
}
3. 在 MCViewController
控制器里面,添加tableView,显示出cell。遵从cell的代理<MCTableViewCellDelegate>
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法实现cell代理
即
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MCTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"aCell"];
MCModel *model = self.dataSource[indexPath.row];
// 利用model传值
cell.model = model;
// 在这里设置代理
cell.delegate = self;
return cell;
}
然后遵从代理, 利用block把当前页面的 model 传过去 ,传到上级页面,先在当前页面声明block
// 声明block, 利用block 传值
typedef void(^MCBlock)(MCModel *model);
@interface MCViewController : UIViewController
@property (nonatomic, copy) MCBlock modelBlock;
@end
接着在当前页面实现方法
// 遵循代理
- (void)receiveModel:(MCModel *)model
{
[self dismissViewControllerAnimated:NO completion:nil];
if (self.modelBlock) {
// 传值
self.modelBlock(model);
}
}
4. 在上级页面 ViewController
中接收传过来的model,
- (IBAction)pushNextView:(UIButton *)sender {
MCViewController *vc = [[MCViewController alloc] init];
// 在这里接收 block 传过来的值
vc.modelBlock = ^(MCModel * _Nonnull model) {
self.titleLabel.text = model.title;
self.addressLabel.text = model.address;
};
[self presentViewController:vc animated:NO completion:nil];
}
代码:https://gitee.com/httpshuoshuo123w/click_cell_to_pass_model