使用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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章