使用Block传值的常用实例

这里写图片描述

问题:viewControllerB需要拿到viewControllerA的itemView里的Model,进行相应的信息设置。Model该如何传递过去?

/*
Model –> ItemView –> ListView : [itemClick:] —> A : [itemClickBlock(model) ] —> A : [performSegueWithIdentifier:sender] —> A : [ prepareForSegue:] –> B
*/

ItemView

@interface ItemView : UIView
@property (nonatomic, strong) Model *model;
@end

Model

@interface Model : NSObject
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *intro;
@end

ListView

@interface ListView : UIScrollView
// 定义一个block进行传值, 要想拥有一个block属性,只能用copy 
@property (nonatomic, copy) void (^itemClickBlock)(Model *model);
@end

@implementation ListView
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // 加载关卡信息
        [self loadStageInfo];
    }
    return self;
}

-(void)loadStageInfo{
    //先取出itemView。。。。
    [itemView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(itemClick:)]];
}

#pragma mark 点击了关卡
- (void)itemClick:(UITapGestureRecognizer *)tap
{
    if (_itemClickBlock) {
        ItemView *itemView =  (ItemView *)tap.view;
        _itemClickBlock(itemView.model);
    }
}
@end

ViewControllerA

@implementation ViewControllerA

- (void)viewDidLoad
{
    [super viewDidLoad];
    // 2.添加ListView
    ListView *listView = [[ListView alloc] initWithFrame:self.view.bounds];

    listView.itemClickBlock = ^(Model *model){
        // MyLog(@"%@", model.title); 这里就可以拿到model里的属性
        [self performSegueWithIdentifier:@"segue" sender:model];
    };
    // 这里用insert保证listView在最下层
    [self.view insertSubview:listView atIndex:0];
}

#pragma mark 跳转之前会调用(一般在这里传递数据给下一个控制器)
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    ViewControllerB *ready = segue.destinationViewController;
    ready.model = sender;
}

ViewControllerB

#import <UIKit/UIKit.h>
@class Model;

@interface ViewControllerB : UIViewController
// 关卡信息
@property (nonatomic, strong) Model *model; //model传进来可以赋值了
@property (weak, nonatomic) IBOutlet UILabel *stageNo;
@property (weak, nonatomic) IBOutlet UILabel *stageIntro;
@property (weak, nonatomic) IBOutlet UIImageView *stageIcon;

- (IBAction)back;
@end
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章