Ios UItableVIew reusableCell在滚动后在随机单元格中添加按钮?
我有一个带有Ios UItableVIew reusableCell在滚动后在随机单元格中添加按钮?,ios,uitableview,Ios,Uitableview,我有一个带有ReusableCellWithIdentifier的tableview,我正在寻找最好的解决方案。 我不想使用下面这样的removesubview方法 if ([cell.contentView subviews]){ for (UIBUtton *subview in [cell.contentView subviews]) { [subview removeFromSuperview]; } } 这是我的cellForRowAtIndexPat
ReusableCellWithIdentifier
的tableview,我正在寻找最好的解决方案。
我不想使用下面这样的removesubview方法
if ([cell.contentView subviews]){
for (UIBUtton *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
}
这是我的cellForRowAtIndexPath方法我习惯于使用tag属性返回按钮。但在滚动时,此按钮会添加到diff部分的diff行中
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdetifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdetifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdetifier];
}
if ((indexPath.section==1 && indexPath.row==0) || (indexPath.section==3 && indexPath.row==1)) {
cell.accessoryView = [self buttonWithMap:cell];
}
return cell;
}
创建按钮
- (UIButton *)buttonWithMap:(UITableViewCell *)cell
{
UIButton *btn=(UIButton *)[cell.contentView viewWithTag:101];
if (btn) {
return btn;
}
else{
UIButton *btnLocation = [UIButton buttonWithType:UIButtonTypeCustom];
btnLocation.backgroundColor = [UIColor clearColor];
btnLocation.frame = CGRectMake(0, 0, 20, 20);
[btnLocation setImage:[UIImage imageNamed:@"map_location.png"] forState:UIControlStateNormal];
[btnLocation addTarget:self action:@selector(setAddressBySelectLocation:) forControlEvents:UIControlEventTouchUpInside];
[btnLocation setTag:101];
return btnLocation;
}
}
我相信当条件不满足时,您需要将其设置为nil,否则
tableView
会混淆:
if ((indexPath.section==1 && indexPath.row==0) || (indexPath.section==3 && indexPath.row==1)) {
cell.accessoryView = [self buttonWithMap:cell];
}else{
cell.accessoryView = nil;
}
子类UITableViewCell然后您可以在prepareforeuse:@CW0007007中“重置”您的单元格,但是这段代码有什么问题呢。为什么我需要子类?@Sunnyshah当它重用一个单元格时,它仍然会有它重用的单元格的附件视图,所以你必须明确地删除旧的附件视图,即使你没有用任何东西替换它。@AlexBlundell但我只为节的特定行添加了附件视图。重用一个单元格可以查看另一个单元格?子类化将使它更容易处理UI变化很大的显式单元格情况。您的代码对我很有用。但仅为节的特定行添加单元格访问视图。那么,为什么要对所有行执行此操作呢?我知道它仅适用于这两个部分,但当它不是这些部分时,您仍然需要添加代码,因为单元格正在被重用