使用Block传值的常用实例

本文介绍了一种在iOS应用中实现从一个视图控制器到另一个视图控制器传递Model对象的方法。通过使用block来捕获点击事件并传递数据,再结合prepareForSegue方法,实现了ViewControllerA向ViewControllerB的数据传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里写图片描述

问题: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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值