整理一下 通知传值 Block传值

本文介绍了在iOS开发中,UICollectionView如何通过Block和NSNotification两种方式实现界面间的传值操作。包括在CollectionViewCell点击时如何调用Block传递indexPath,以及如何利用NSNotification进行数据通知。

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

 

 Block:

一、

(1)

在需要传值的界面定义属性

// 点击collectionViewCell的回调
@property (nonatomic, copy) void(^DidcollectionClick)(NSIndexPath *indexPath);

在按钮或者手势 或者代理方法中 执行block

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//这里执行block self.DidcollectionClick(indexPath); }

(2)

在接收界面 中

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == 1) {
        ManageMoneyViewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ManageMoneyViewTableViewCell class])];
        // 接收block 传过来的值
        cell.DidcollectionClick = ^(NSIndexPath *indexPath) {
            NSLog(@"%ld",(long)indexPath.row);
            
        };
        cell.dataArray = self.bankListdataArray;
        return cell;
    }
    if (tableView.tag == 2) {
        ManageMoneynewsTableViewCell *cell = [[ManageMoneynewsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ManageMoneynewsTableViewCell"];
//        cell.dataArray = self.dataArray;
        return cell;
    }
    return nil;
}

 

 

通知:

一、接收通知的控制器 (监听通知)

- (void)viewDidLoad {// 注册一个通知监听 接收通知
    NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
    [notiCenter addObserver:self selector:@selector(receiveNotification:) name:NotificManage object:nil];
}
// @selector(receiveNotification:)方法,监听到通知后 执行
- (void)receiveNotification:(NSNotification *)noti
{
    
    // NSNotification 有三个属性,name, object, userInfo,其中最关键的object就是从第三个界面传来的数据。name就是通知事件的名字, userInfo是一个字典 也可以把数据通过字典传递过来(如果要传的数据多的时候)
    NSLog(@"%@ === %@ === %@", noti.object, [noti.userInfo objectForKey:@"rowId"], noti.name);
    
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

二、发送通知

// 这段代码 发送通知
    NSNotificationCenter *postCenter = [NSNotificationCenter defaultCenter];
    // 发送通知. postNotificationName必须和接收通知的postNotificationName名一致, object就是要传的值。 UserInfo是一个字典, 如果要用的话,提前定义一个字典, 可以通过这个来实现多个参数的传值使用。
    NSMutableDictionary *postDic = [NSMutableDictionary dictionary];
    [postDic setValue:[NSString stringWithFormat:@"%ld",(long)indexPath.row] forKey:@"rowId"];
    [postCenter postNotificationName:NotificManage object:@"成功" userInfo:postDic];

 

转载于:https://www.cnblogs.com/dujiahong/p/7495242.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值