UITableView 自定义cell上面的按钮点击事件

如果需要在控制器中实现按钮的点击事件并且获得对应某行cell的数据,可以用代理的方法,代码如下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HLLocalAccountCell *cell = [HLLocalAccountCell localAccountCellWithTableView:tableView];
    cell.delegate = self;//自定义cell的代理,下面会写到cell的代理
    cell.model = self.accounts[indexPath.row];
    cell.tag = indexPath.row; //传递tag
    return cell;
    
}

在cell.h中:

@protocol CardCellBtnDelegate <NSObject>

- (void)choseCards:(UIButton *)button;

@end
@property (nonatomic,weak)id<CardCellBtnDelegate>delegate;

cell.m:

//cell上的按钮的点击事件
- (void)selBtn:(UIButton *)btn {
    _selBtn.selected = !btn.selected;
    if ([_delegate respondsToSelector:@selector(choseCards:)]) {
        btn.tag = self.tag;
        [_delegate choseCards:btn];
    }
}

然后在控制器的.m文件中执行代理方法:(别忘了继承协议)

#pragma mark - HLLocalAccountCell Delegate
- (void)choseCards:(UIButton *)button {
    NSInteger row1 = button.tag;
    HLLocalAccountModel *model = self.accounts[row1];//获得了model就获得了数据
    NSString *str = [NSString stringWithFormat:@"%li#%@#%@",model.accType,model.accNo,model.accName];
    if (button.selected == YES) {
        [arrM addObject:str];
    }else {
        [arrM removeObject:str];
    }
    NSLog(@"---------%@",arrM);
    //用","拼接数组内的字符串
    NSString *str1 = [arrM componentsJoinedByString:@","];
    NSLog(@"==========%@",str1);
    mulParams = [NSMutableDictionary dictionaryWithDictionary:self.params];
    [mulParams setValue:str1 forKey:@"account_info"];
    
}

先写这么多,以后继续补充

 点击对应的cell间接改变自定义cell上btn的属性

在model中声明一个isSelect属性,在控制器中写  cell.model.isSelect = !cell.model.isSelect;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //获取点击对应的cell
    HLLocalAccountCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.model.isSelect = !cell.model.isSelect;
    cell.model = self.accounts[indexPath.row];
    NSString *str = [NSString stringWithFormat:@"%li#%@#%@",cell.model.accType,cell.model.accNo,cell.model.accName];
    if (cell.model.isSelect == YES) {
        [arrM addObject:str];
    }else {
        [arrM removeObject:str];
    }
    //用","拼接数组内的字符串
    NSString *account_info = [arrM componentsJoinedByString:@","];
    //    NSLog(@"==========%@",str1);
    mulParams = [NSMutableDictionary dictionaryWithDictionary:self.params];
    [mulParams setValue:account_info forKey:@"account_info"];
}

在cell.m中:

- (void)setModel:(HLLocalAccountModel *)model {
    _model = model;

    
    if (model.isSelect == YES) {
        _selBtn.selected = YES;
    }else {
        _selBtn.selected = NO;
    }
    
}

 

posted @ 2016-03-23 11:54  将心放逐  阅读(1569)  评论(0编辑  收藏  举报