iOS之用Block实现cell上的按钮点击事件

写这篇文章纯属打发时间用......

需求:cell的按钮点击事件的实现,如图
cell上的添加到购物车按钮.png

在cell.h文件中 先定义一个block

#import <UIKit/UIKit.h>

@class XSMyFavoriteTableViewCell;

//声明一个名为 AddToCartsBlock  无返回值,参数为XSMyFavoriteTableViewCell 类型的block
typedef void (^AddToCartsBlock) (XSMyFavoriteTableViewCell *);

@interface XSMyFavoriteTableViewCell : UITableViewCell

@property(nonatomic, copy) AddToCartsBlock addToCartsBlock;

@end

在cell.m的文件中

- (IBAction)addToShoppingCart:(UIButton *)sender {
    if (self.addToCartsBlock) {
        self.addToCartsBlock(self);
    }
}

在controller中,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XSMyFavoriteTableViewCell *cell = (XSMyFavoriteTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    __weak typeof(self) weakSelf = self;
    cell.addToCartsBlock = ^(XSMyFavoriteTableViewCell *cell) {
        [weakSelf myFavoriteCellAddToShoppingCart:cell];
    };
    return cell;
}
- (void)myFavoriteCellAddToShoppingCart:(XSMyFavoriteTableViewCell *)cell{
        NSLog(@"点击了添加到购物车");
}

同理,这个需求用代理也同样能实现,具体看个人喜好咯。
而本人的另一篇文章iOS将数据从controller里分离出来减轻controller的压力也正是利用了block传值而得以实现的。
以上。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容