TableView 是自帶滑動刪除這個功能,但是有時候并不能滿足我們的需求。例如,需求要求刪除的那個按鈕可自定義,這時候系統的功能就嗝屁了...
當然,現在好用的輪子那么多,相信肯定有能滿足你要求的。今天,我來教大家怎么保持系統的滑動刪除功能不變,又可以隨意的自定義刪除按鈕,快捷方便!
廢話不多說,先上圖:
開啟TableView 的滑動刪除功能
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"BtnClick_%zd",indexPath.row);
}-
自定義一個 UITableViewCell
實現如下方法:
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
UIView *deleteBgView = [UIView new];
deleteBgView.backgroundColor = [UIColor brownColor];
[self.contentView addSubview:deleteBgView];UIButton *deleteBtn = [UIButton new]; //deleteBtn.backgroundColor = [UIColor yellowColor]; [deleteBtn setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal]; [deleteBgView addSubview:deleteBtn]; [deleteBgView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.offset([UIScreen mainScreen].bounds.size.width); make.top.equalTo(self.contentView); make.bottom.equalTo(self.contentView).offset(1); make.width.equalTo(self.contentView); }]; [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) { make.width.offset(80); make.top.equalTo(deleteBgView); make.bottom.equalTo(deleteBgView); make.left.equalTo(deleteBgView); }]; } return self; }
這里我用了 Masonry 來做布局約束,相信大家一定不陌生,到這里基本完成了,iOS7,8,9 親測無誤,輕松愉快!
注: 這種做法只適用于一個按鈕的情況,多個按鈕的情況因為無法觸發按鈕的點擊事件,所以無從下手,研究出來的小伙伴,望告知!