轉自:http://www.cnblogs.com/cao-yan/p/5122995.html
如有侵犯,請來信:oiken@QQ.com
一. 需求: cell的側滑刪除默認只有一個刪除按鈕, 給側滑添加多個按鈕, '刪除', '置頂', '更多'.
二. 實現說明:
1) 我們在使用一些應用的時候,在滑動一些聯系人的某一行的時候,會出現刪除、置頂、更多等等的按鈕,在iOS8之前,我們都需要自己去實現。但是到了iOS8,系統已經寫好了,只需要一個代理方法和一個類就搞定了
2) iOS8的協議多了一個方法,返回值是數組的tableView:editActionsForRowAtIndexPath:方法,我們可以在方法內部寫好幾個按鈕,然后放到數組中返回,那些按鈕的類就是UITableViewRowAction
3) 在UITableViewRowAction類,我們可以設置按鈕的樣式、顯示的文字、背景色、和按鈕的事件(事件在Block中實現)
4) 在代理方法中,我們可以創建多個按鈕放到數組中返回,最先放入數組的按鈕顯示在最右側,最后放入的顯示在最左側
5) 注意:如果我們自己設定了一個或多個按鈕,系統自帶的刪除按鈕就消失了.
三. 代碼實現:
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 添加一個'刪除'按鈕
UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"刪除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
NSLog(@"點擊了'刪除'");
// 1. 更新數據
// 2. 更新UI
// [tableView deleteRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
}];
// 添加一個'置頂'按鈕
UITableViewRowAction *toPRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"置頂" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
NSLog(@"點擊了'置頂'");
// 1. 更新數據
// 2. 更新UI
//NSIndexPath *firstIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
//[tableView moveRowAtIndexPath:indexPathtoIndexPath:firstIndexPath];
}];
topRowAction.backgroundColor = [UIColor blueColor];
// 添加一個'更多'按鈕
UITableViewRowAction *moreRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"更多" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
NSLog(@"點擊了'更多'");
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
}];
moreRowAction.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
//將設置好的按鈕放到數組中返回
return@[deleteRowAction, topRowAction, moreRowAction];
}
新聞熱點
疑難解答