visibleCells这个方法在开发中有时会被忽略掉,在进行tableView列表开发的时候,我们会经常和cell打交道。
你可能之前确定点击cell时,要确定当前被点击的cell是列表中的哪一个cell时,我们通常会用遍历的方法,去遍历整个tableView上的所有cell然后自己去逐一判断。但现在有一个更简单的方法,其实这个方法也需要用到遍历,但是如果你在cell上加按钮,那你用传统遍历方法去实现点击事件等就比较麻烦了,用visibleCells就很方便了。
代码如下:
1、我现在的模块中每个cell上都有一个btn按钮,点击这个btn按钮删除对应的cell,这里我是用来删除收货地址列表
#pragma mark -UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *cellid = @"MemberAddressListTableViewCell";
_cell = [_tbvAddress dequeueReusableCellWithIdentifier:cellid];
if (!_cell) {
_cell = [[[NSBundle mainBundle]loadNibNamed:@"MemberAddressListTableViewCell" owner:self options:nil]firstObject];
}
_cell.selectionStyle = UITableViewCellSelectionStyleNone;
self.addressModel = [self.mArrayAddress objectAtIndex:indexPath.section];
[self.cell setCellWithAddress:_addressModel];
//设置cell和cell上按钮的tag值
_cell.tag = indexPath.section;
_cell.btnRemove.tag = indexPath.section;
[_cell.btnRemove addTarget:self action:@selector(btnRemoveAction:) forControlEvents:UIControlEventTouchUpInside];
return _cell;
}
2、下面进入btn点击事件处理方法用visibleCells方法进行判断cell
- (void)btnRemoveAction:(UIButton *)btn{
//visibleCells的返回值其实是一个数组,我们定义一个数组用来接收取到的值。
NSArray *visibleCells = [self.tbvAddress visibleCells];
//实例化cell用for..in 遍历取到的visibleCells这个数组
for (MemberAddressListTableViewCell *cell in visibleCells) {
//在上面的dataSource代理方法中已经设置了cell和btw的各自对应的tag值,现在拿过来使用
if (cell.tag == btn.tag) {
//请求服务器接口,删除服务器数据
[self delAddressList:(NSInteger *)cell.tag];
//然会再清空当前对应的本地数组数据
[self.mArrayAddress removeObjectAtIndex:[cell tag]];
[self.tbvAddress reloadData];
break;
}
}
}
3、请求服务器接口,删除服务器数据和本地数组数据同时进行
#pragma mark - Request Methods
- (void)delAddressList:(NSInteger *)integer{
//取到传进来的integer值,获取对应数组中的数据赋值给model
AddressModel *model = [[AddressModel alloc]init];
model = [self.mArrayAddress objectAtIndex:(int)integer];
NSMutableDictionary *dictParames = [NSMutableDictionary dictionary];
[dictParames safeSetValue:model.id forKey:@"id"];
[[HGHttpRequestManager sharedManager]getRequestWithPamameters:dictParames ToPath:kAPIPathAddressDel success:^(NSDictionary *result) {
AddressListModel *listModel = [[AddressListModel alloc]initWithDictionary:result error:nil];
if (listModel.isValid) {
[self showSucceededHud:listModel.msg];
//如果删除成功,再次拉取列表,刷新UI
[self getAddresssList];
}
if (self.mArrayAddress.count == 0) {
[self showNoAddressView];
}
} failure:^(NSError *error) {
[self showErrorHud:@"删除失败,请稍后重试!"];
}];
}
其实visibleCells就是去获取tableView的上所有的cell,放到自己的数组里,然后在这个数组里去取自己所需要的cell,进行处理。
前提先设置cell和cell上所加控件的tag值,这样就能确定当前点击的btn按钮是不是在当前的cell之上了。
文章为作者原创,转载前请联系我本人,谢谢!
如感觉对你有帮助,请在评论里支持我一下,感谢!