本方法实现的原理是将自定义按钮加在tableViewCell.contentView的屏幕外的frame上,打个比方,如果是5系的话,那么你自定义按钮的frame的起点就在(320+,0)(320+表示大于等于320...),当你滑动,整个cell往左偏移的时候,这时候本应该右边显示为这样:
但是由于我们把自定义的按钮add到屏幕外,此时contentView上的自定义按钮就将原删除按钮给遮住了。然后接下来就是实现删除了,重写-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath方法,有了indexPath就可以将cell删除了,然后刷新tableView即可
覆写的tableViewCell的初始化方法:
- -(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
- self=[super initWithStyle:style reuseIdentifier:reuseIdentifier];
- if (self) {
- _deleteView=[[UIView alloc]initWithFrame:CGRectMake(kScreenWidth, 0, kScreenWidth, 100)];
- _deleteView.backgroundColor=BaseViewBackgroundColor;
- [self.contentView addSubview:_deleteView];
- ButtonItem *deleteBtn=[[ButtonItem alloc]initWithFrame:CGRectMake(0, 0, 80, 100) WithImageName:@"icon_delete" WithImageWidth:48 WithImageHeightPercentInItem:.7 WithTitle:NSLocalizedString(@"DeleteOrder", nil) WithFontSize:14 WithFontColor:[UIColor blackColor] WithGap:-5];
- <span style="white-space:pre"> </span>//ButtonItem是我自己定义的一个控件,下面有介绍,<span style="font-family: Arial, Helvetica, sans-serif;">@"icon_delete"是删除按钮的图片</span>
- [_deleteView addSubview:deleteBtn];
- }
- return self;
- }
覆写tableView的代理方法:
- -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
- [mutableArray removeObjectAtIndex:indexPath.row];
- [tableView reloadData];
- }
当然如果只是这样,你会发现你左划完成之后,你的按钮只会有原delete按钮的宽度,此时就可以再通过如下代理方法进行宽度的调节...
- -(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
- return @"通过改变title的长度,你想多宽就多宽";
- }
Tips:
ButtonItem是我自己写的一个继承于UIControl的控件,上面有UIImageView和UILable,便于我实现那种带图片和文字的按钮
- - (id)initWithFrame:(CGRect)frame WithImageName:(NSString *)imageName WithImageWidth:(CGFloat)imgWidth WithImageHeightPercentInItem:(CGFloat)imgPercent WithTitle:(NSString *)title WithFontSize:(CGFloat)fontSize WithFontColor:(UIColor *)color WithGap:(CGFloat)gap{
- self.backgroundColor=[UIColor clearColor];
- self=[super initWithFrame:frame];
- if (self) {
- _imageView=[[UIImageView alloc]initWithFrame:CGRectMake((frame.size.width-imgWidth)/2, 5, imgWidth, imgPercent*frame.size.height)];
- if (imageName) {
- _imageView.image=[UIImage imageNamed:imageName];
- }
- _imageView.contentMode=UIViewContentModeScaleAspectFit;
- [self addSubview:_imageView];
- _label=[[UILabel alloc]initWithFrame:CGRectMake(0, gap+_imageView.frame.size.height, frame.size.width, (1-imgPercent)*frame.size.height)];
- _label.text=title;
- _label.textColor=color;
- _label.textAlignment=NSTextAlignmentCenter;
- _label.font=[UIFont systemFontOfSize:fontSize];
- [self addSubview:_label];
- }
- return self;
- }