我有ReusableCellWithIdentifier
的桌面我正在尋找最佳解決方案。 我不想使用removesubview方法如下面UItableVIew reusableCell在滾動後在隨機單元格中添加按鈕?
if ([cell.contentView subviews]){
for (UIBUtton *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
}
,這裏是我的cellForRowAtIndexPath方法。 我用來讓Button返回標籤屬性。但在滾動時,此按鈕被添加到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;
}
創建Buttonn
- (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;
}
}
子類的UITableViewCell那麼你就可以 '復位'你的單元格在prepareForReuse: – CW0007007
@ CW0007007但是這個代碼有什麼問題。爲什麼我需要子類? –
@Sunnyshah當它重用一個單元格時,它仍然具有它重用的單元格的輔助視圖,因此即使您沒有替換它,也必須明確刪除舊的輔助視圖。 –