一、概述
UITbableView作為列表展示信息,除了展示的功能,有時(shí)會(huì)用到刪除的功能,比如購(gòu)物車
,視頻收藏
等。刪除功能可以直接使用系統(tǒng)自帶的刪除功能,當(dāng)橫向向左輕掃cell時(shí),右側(cè)出現(xiàn)紅色的刪除按鈕,點(diǎn)擊刪除當(dāng)前cell。
二、效果圖
效果圖.gif
三、技術(shù)分析
- 讓tableView進(jìn)入編輯狀態(tài),即
tableView.editing = YES
。
// 取消
[self.tableView setEditing:YES animated:NO];
- 返回編輯模式,即實(shí)現(xiàn)
UITableViewDelegate
中的- tableview:editingStyleForRowAtIndexPath:
方法,在里面返回刪除模式。如果不實(shí)現(xiàn),默認(rèn)返回的就是刪除模式。
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 刪除
return UITableViewCellEditingStyleDelete;
}
- 提交刪除操作,即實(shí)現(xiàn)
UITableViewDelegate
中的- tableview:commitEditingStyle:editing StyleForRowAtIndexPath:
方法。只要實(shí)現(xiàn)此方法,即默認(rèn)實(shí)現(xiàn)了系統(tǒng)橫掃出現(xiàn)刪除按鈕的刪除方法。
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
//只要實(shí)現(xiàn)這個(gè)方法,就實(shí)現(xiàn)了默認(rèn)滑動(dòng)刪除!!!!!
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// 刪除數(shù)據(jù)
[self _deleteSelectIndexPath:indexPath];
}
}
- 如果想把刪除按鈕改為中文,可以實(shí)現(xiàn)
-tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:
方法。
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"刪除";
}
四、細(xì)節(jié)處理
- 以下屬性必須設(shè)置為NO,默認(rèn)為NO,否則會(huì)導(dǎo)致
刪除模式
無(wú)效,反而成為多選模式
。
tableView.allowsMultipleSelection = NO;
tableView.allowsSelectionDuringEditing = NO;
tableView.allowsMultipleSelectionDuringEditing = NO;
- 側(cè)滑狀態(tài)下點(diǎn)擊
編輯
按鈕的bug。
// 編輯按鈕被點(diǎn)擊
- (void)_rightBarButtonItemDidClicked:(UIButton *)sender
{
sender.selected = !sender.isSelected;
if (sender.isSelected) {
// 這個(gè)是fix掉:當(dāng)你左滑刪除的時(shí)候,再點(diǎn)擊右上角編輯按鈕, cell上的刪除按鈕不會(huì)消失掉的bug。且必須放在 設(shè)置tableView.editing = YES;的前面。
[self.tableView reloadData];
// 取消
[self.tableView setEditing:YES animated:NO];
}else{
// 編輯
[self.tableView setEditing:NO animated:NO];
}
}
五、期待
- 文章若對(duì)您有點(diǎn)幫助,請(qǐng)給個(gè)喜歡??;若沒(méi)啥幫助,請(qǐng)給點(diǎn)建議。
- 針對(duì)文章所述,您閱讀有什么疑問(wèn);或使用Demo中有什么bug。請(qǐng)?jiān)谖恼碌撞吭u(píng)論,我會(huì)盡快解決問(wèn)題。
- GitHub地址:https://github.com/CoderMikeHe