-
Notifications
You must be signed in to change notification settings - Fork 6
制作可以滑动操作的TableViewCell
CoderYoung edited this page Sep 15, 2015
·
2 revisions
之前发过一篇文章TableView编辑模式
里面有一个小节说明了iOS7之前如何制作可以滑动操作的TableViewCell,制作过程极其蛋疼。
iOS8之后,苹果终于提供API给开发者了,废话少说,上代码
##iOS8新增的API
typedef NS_ENUM(NSInteger, UITableViewRowActionStyle) {
UITableViewRowActionStyleDefault = 0,
UITableViewRowActionStyleDestructive = UITableViewRowActionStyleDefault,
UITableViewRowActionStyleNormal
} NS_ENUM_AVAILABLE_IOS(8_0);
NS_CLASS_AVAILABLE_IOS(8_0) @interface UITableViewRowAction : NSObject <NSCopying>
+ (instancetype)rowActionWithStyle:(UITableViewRowActionStyle)style title:(NSString *)title handler:(void (^)(UITableViewRowAction *action, NSIndexPath *indexPath))handler;
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0);
##实现代码
/**
* 必须重写,否则只有进入编辑模式才能滑动cell
*
*/
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
// 删除
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.arrayValue removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
/**
* cell添加滑动显示按钮
*
*/
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
//设置删除按钮
UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除"handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
[self.arrayValue removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}];
//设置收藏按钮
UITableViewRowAction *collectRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"收藏"handler:^(UITableViewRowAction *action,NSIndexPath *indexPath) {
collectRowAction.backgroundColor = [UIColor greenColor];
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"收藏" message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
}];
//设置置顶按钮
UITableViewRowAction *topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"置顶" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
[self.arrayValue exchangeObjectAtIndex:indexPath.row withObjectAtIndex:0];
NSIndexPath *firstIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
[tableView moveRowAtIndexPath:indexPath toIndexPath:firstIndexPath];
}];
topRowAction.backgroundColor = [UIColor blueColor];
// collectRowAction添加毛玻璃特效
collectRowAction.backgroundEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
collectRowAction.backgroundColor = [UIColor grayColor];
return @[deleteRowAction,collectRowAction,topRowAction];
}
##效果图