iOS block用法

最近在学习的过程中遇到一个问题,整个项目用UINavigationController作为根控制器,某一个表试图控制器使用了自定义的UITableViewCell,该类cell有自定义的几个按钮,当点击cell的任何一个按钮时需要知道当前是哪个cell以及哪个按钮被点击然后做相应的事件响应(更改该行数据,页面跳转等),之前用过代理,这一次想换一种方式,所以选择了用块来代替,下面列出详细步骤

1.在自定义的cell头文件中申明块,并定义相应的块类型

#import <UIKit/UIKit.h>

@class ShopingCartTableViewCell;

//块申明

typedef void(^reduceGoodNumS)(ShopingCartTableViewCell *);

typedef void(^addGoodNumS)(ShopingCartTableViewCell *);

typedef void(^selectGoodS)(ShopingCartTableViewCell *);


@interface ShopingCartTableViewCell : UITableViewCell

//相应的块变量定义

@property (strong, nonatomic) reduceGoodNumS reduceGoodNumBlock;

@property (strong, nonatomic) addGoodNumS addGoodNumBlock;

@property (strong, nonatomic) selectGoodS selectGoodBlock;


@end

2.在使用自定义cell填充表格的地方,实现块功能,这里以添加商品数量为例,减少商品数量和选中商品数量同下

        //添加商品数量block

        cell.addGoodNumBlock = ^(ShopingCartTableViewCell *cell)

        {

            NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

            NSDictionary *goodsDic = [self.dataSource objectAtIndex:indexPath.section];

            NSArray *goodsArray = [goodsDic objectForKey:@"array"];

            self.good = [goodsArray objectAtIndex:indexPath.row];

    

            self.good.num = [cell.numTF.text intValue]+1;

            //            增加商品数量

            if ([self alertNum])

            {

                cell.numTF.text = [NSString stringWithFormat:@"%d",[cell.numTF.text intValue] + 1];

            }

            //            修改总金额

            if (cell.checkboxBtn.selected)

            {

                [self alertSelecedGoodNum];

                //            计算价格

                [self alertSum];

                indexPath = [NSIndexPath indexPathForRow:0 inSection:self.dataSource.count];

                NSArray *indexArray=[NSArray arrayWithObject:indexPath];

                [self.tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];

            }

        };



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值