iOS 点击cell同步cell中添加的UIButton控件
2017-04-27 本文已影响374人
WLZero
我们在做购物车或者多选功能的时候经常会遇到点击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;
}
}
}
}
如有错误,欢迎指正。