很多人對(duì)于左滑刪除cell都不太會(huì),我今天花了點(diǎn)時(shí)間看了下這個(gè)系統(tǒng)原生的左滑刪除cell,很簡單,分幾步走就可以了。
第一步,就是簡單的創(chuàng)建列表tableview,然后就是設(shè)置
self.tableView.delegate = self;
self.tableView.datasource = self;
接下來就是簡單的實(shí)現(xiàn)代理方法了。
-(NSInteger) numberOfSectionsInTableView:(UITableView)tableView
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
這四個(gè)基本方法自不用多說,大家都知道的,接下來就是一些刪除要用到的方法。
第一個(gè):
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
其實(shí)很多方法看名字就知道可以實(shí)現(xiàn)什么,這個(gè)方法就是問你可不可以進(jìn)行編輯,編輯里面包括很多東西,也包括刪除這個(gè)事件??捶祷刂凳荵ES還是NO,YES就是可以編輯,反之就是不可以唄,當(dāng)然,你也可以根據(jù)條件判斷,哪一行可以編輯,哪一行不可以編輯。
第二個(gè):
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
這個(gè)就是返回單元格的編輯風(fēng)格,你是要做什么樣的編輯呢,這里只說做刪除編輯,所以直接返回return UITableViewCellEditingStyleDelete;就是代表刪除的。
返回return UITableViewCellEditingStyleInsert;這樣的就是插入的。
第三個(gè):
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
接下來就是一個(gè)比較個(gè)性化的設(shè)置方法。就是自定義刪除按鈕的名稱,想顯示啥就顯示啥,差不多就行,return @"刪除";像這樣就可以了
第四個(gè):
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[self.dataArr removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
}
else
{
[self.dataArr addObject:@100];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:self.dataArr.count - 1 inSection:0];
[tableView insertRowsAtIndexPaths:@[newIndexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
這個(gè)方法我個(gè)人認(rèn)為應(yīng)該算是最重要的方法了,無論你的列表里面有沒有數(shù)據(jù),這個(gè)方法你都應(yīng)該寫上,一般的列表上顯示的數(shù)據(jù)都是由數(shù)組或者字典里的數(shù)據(jù)提取出來的,這個(gè)方法中你就需要在你提取數(shù)據(jù)的源頭進(jìn)行刪除數(shù)據(jù),不然即使及刪除了列表的行,也不管用,那條數(shù)據(jù)還是會(huì)顯示出來,或者什么地方?jīng)]弄好,直接是報(bào)錯(cuò),所以要注意這一點(diǎn)。在刪除模式中,順序很重要,稍微出一點(diǎn)錯(cuò)就會(huì)崩潰。像我上面寫的,要根據(jù)所在行刪除數(shù)組對(duì)應(yīng)的數(shù)據(jù),然后是更新界面。下面的那個(gè)else里面就是插入操作。
這樣就是基本完成了左滑刪除的功能。
(要是有哪些地方錯(cuò)了請(qǐng)指正我,我也是初學(xué)者,希望與大家共同學(xué)習(xí),共同進(jìn)步)
tableviewcell的左滑刪除Demo
這個(gè)demo里面我加了一個(gè)自定義的cell,注釋啥的也怎么加,要是真有人下載了,有看不明白的就直接留言找我就可以了哈。。。