在UITableViewCell中添加自定义编辑和删除按钮

时间:2015-10-12 05:53:12

标签: ios objective-c uitableview tableviewcell

我有UITableView,其中包含所有国家/地区的名称。 用户可以通过点击cell

随时删除或修改国家/地区的名称

我的UITableView单元格最初看起来像这样:

enter image description here

现在,当用户点击它时,我正在改变它:

enter image description here

我认为我正在采取一种非常蹩脚的方法。这就是我所做的:

声明要添加的全局按钮:

 UIButton *btnDeleteWithImage,*btnDeleteWithText,*btnEditWithImage,*btnEditWihtText; //buttons

NSMutableArray跟踪indexPath.row

现在我的didSelectMethod我这样做:

 //To change the background 
 UIView *selectionBackground = [[UIView alloc] init];

  selectionBackground.backgroundColor = [UIColor customColor];

 cell.selectedBackgroundView = selectionBackground;

 // to check which cell is pressed

if([indexPathCollection containsObject:index])
{
    [btnDeleteWithImage removeFromSuperview];
    [btnDeleteWithText removeFromSuperview];
    [btnEditWihtText removeFromSuperview];
    [btnEditWithImage removeFromSuperview];
    [indexPathCollection removeObject:index];

    [cell addSubview:btnDeleteWithImage];
    [cell addSubview:btnDeleteWithText];
    [cell addSubview:btnEditWithImage];
    [cell addSubview:btnEditWihtText];
    [indexPathCollection addObject:index];
}
else
{

    [cell addSubview:btnDeleteWithImage];
    [cell addSubview:btnDeleteWithText];
    [cell addSubview:btnEditWithImage];
    [cell addSubview:btnEditWihtText];
    [indexPathCollection addObject:index];
}

但是这不能正常工作。当我滚动表格编辑和随机删除按钮时。

有人有更好的想法如何以非常有效的方式实现这一目标。

2 个答案:

答案 0 :(得分:2)

您可以通过创建包含属性的自定义单元格来实现此目的

CustomCell.h

@interface CustomCell : UITableViewCell

@property (nonatomic, strong) UIButton *btnDeleteWithImage;
@property (nonatomic, strong) UIButton *btnDeleteWithText;
@property (nonatomic, strong) UIButton *btnEditWithImage;
@property (nonatomic, strong) UIButton *btnEditWithText;

@end

在单元格的init方法中初始化它们,首先隐藏它们,或者你可以

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *customCellIdentifier = @"customCellIdentifier";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:customCellIdentifier];

    if (!cell) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:customCellIdentifier];
        // or you can initialize and add them to the cell here
    }
    //here you can modify them accordingly
    return cell;
}

然后委托方法可以是

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    CustomCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [cell.btnDeleteWithImage setHidden:NO];
    [cell.btnEditWithImage setHidden:NO];
}

答案 1 :(得分:1)

最简单的方法是不重复使用单元格。 &安培;使用相同的标识注册您的自定义单元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

customCell* cell = [[customCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:@"indentifire"] ;                                      

// manage your plooting here ..

return cell;
}

希望它适合你。