iOS block用法

来源:互联网 发布:红杉资本 人工智能 编辑:程序博客网 时间:2024/05/08 10:21

最近在学习的过程中遇到一个问题,整个项目用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.tableViewindexPathForCell:cell];

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

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

            self.good = [goodsArrayobjectAtIndex:indexPath.row];

    

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

            //            增加商品数量

            if ([selfalertNum])

            {

                cell.numTF.text = [NSStringstringWithFormat:@"%d",[cell.numTF.textintValue] + 1];

            }

            //            修改总金额

            if (cell.checkboxBtn.selected)

            {

                [self alertSelecedGoodNum];

                //            计算价格

                [self alertSum];

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

                NSArray *indexArray=[NSArrayarrayWithObject:indexPath];

                [self.tableViewreloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];

            }

        };



0 0
原创粉丝点击