我們在做購物車或者多選功能的時候經(jīng)常會遇到點擊tableView中的一個cell,然后該選項被選中或被取消選中。下面我為大家分享一下我的做法。
演示圖
先聲明數(shù)組:
@property(nonatomic,strong)NSMutableArray*selectArr;//選擇的文章數(shù)組
@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;
}
關(guān)鍵用tag作關(guān)聯(lián):
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath{
[tableViewdeselectRowAtIndexPath:indexPathanimated:YES];
UIButton *senderBtn = [self.view viewWithTag:indexPath.row + 100];
[self selectBtnAction:senderBtn];
}
點擊按鈕的觸發(fā)方法:
-(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;
}
}
}
}
如有錯誤,歡迎指正。