您的位置:首页 > 移动开发 > IOS开发

iOS开发 iOS8系统新出cell侧滑View

2015-09-07 10:29 615 查看
侧滑删除、置顶、取消关注,在iOS8之前需要我们自定义,iOS8时苹果公司推出了新的API,UITableViewRowAction类

1.OC版本

// 必须写的方法,和editActionsForRowAtIndexPath配对使用,里面什么不写也行
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

}

// 添加自定义的侧滑功能
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
// 添加一个删除按钮

UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {

NSLog(@"删除按钮");
}];

UITableViewRowAction *topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"置顶" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
NSLog(@"置顶按钮");

}];
topRowAction.backgroundColor = [UIColor orangeColor];

UITableViewRowAction *cancelRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"取消关注" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
NSLog(@"取消关注按钮");
}];

return @[deleteRowAction,topRowAction,cancelRowAction];

}


2.swift版本

// 和editActionsForRowAtIndexPath配对使用
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}

// iOS8 才有此方法
// 这里可以添加任意多个操作。要确保这个代码生效,还是需要实现commitEditingStyle这个方法,哪怕commitEditingStyle里面什么也不处理
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
let deleteRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "删除") { (UITableViewRowAction, NSIndexPath) -> Void in
// 先移除数据源数据
self.dataArray.removeObjectAtIndex(indexPath.row)
// 再动态刷新UITableView
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
}

let topRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "置顶") { (UITableViewRowAction, NSIndexPath) -> Void in
println("置顶按钮点击了")
// 先移除数据源数据
var tempObject: AnyObject = self.dataArray.objectAtIndex(indexPath.row)
self.dataArray.removeObjectAtIndex(indexPath.row)
self.dataArray.insertObject(tempObject, atIndex: 0)
self.tableView.reloadData()
//self.tableView.reloadData()
}
topRowAction.backgroundColor = UIColor.orangeColor()

let cancelRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "取消关注") { (UITableViewRowAction, NSIndexPath) -> Void in
println("取消关注按钮点击了")
self.navigationController?.popToRootViewControllerAnimated(true)
}

if indexPath.row == 0 {
return [deleteRowAction,cancelRowAction]
}else {
return [deleteRowAction,topRowAction,cancelRowAction]
}

}


效果如图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: