iOS 点击cell同步cell中添加的UIButton控件

5 篇文章 0 订阅
3 篇文章 0 订阅

我们在做购物车或者多选功能的时候经常会遇到点击tableView中的一个cell,然后该选项被选中或被取消选中。下面我为大家分享一下我的做法。

演示图

先声明数组:

@property(nonatomic,strong)NSMutableArray*selectArr;//选择的文章数组
@property(nonatomic,strong)NSMutableArray*dataArr;

在tableView的代理里面:

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{

MyArticleModel *model = self.dataArr[indexPath.row];
static NSString *CellId = @"cell";
SelectArticlesCell *cell = [tableViewdequeue ReusableCellWithIdentifier:CellId];
if(cell ==nil) {
cell = [[NSBundlemainBundle] loadNibNamed:@"SelectArticlesCell"owner:selfoptions:nil].firstObject;
}
cell.titleLabel.text= model.title;
cell.sourceLabel.text= model.source;
cell.click_sumLabel.text= model.labels;
[cell.imgV1 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",model.images]] placeholderImage:[UIImageimageNamed:@"nopicture"]];
cell.selectBtn.tag = indexPath.row+100;
[cell.selectBtn addTarget:selfaction:@selector(selectBtnAction:) forControlEvents:UIControlEventTouchUpInside];
if(self.selectArr.count != 0)
{
for(NSString *selectStrinself.selectArr)
{
if([selectStr isEqualToString:[NSString stringWithFormat:@"%ld",indexPath.row]])
{
cell.selectBtn.selected=YES;
break;
}
}
}
returncell;
}

关键用tag作关联:

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
[tableViewdeselectRowAtIndexPath:indexPathanimated:YES];
UIButton *senderBtn = [self.view viewWithTag:indexPath.row + 100];
[self selectBtnAction:senderBtn];
}

点击按钮的触发方法:

-(void)selectBtnAction:(UIButton*)sender{
sender.selected= !sender.selected;
NSString *senderTagStr = [NSString stringWithFormat:@"%ld",sender.tag-100];
if(sender.selected) 
{
[self.selectArr addObject:senderTagStr];
}
else{
for(NSString * selectStr in self.selectArr) 
{
if([selectStris EqualToString:senderTagStr])
 {
[self.selectArr removeObject:selectStr];
break;
}
}
}
}

如有错误,欢迎指正。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值