首页 > 学院 > 开发设计 > 正文

UITableViewCell 原生左滑菜单使用

2019-11-09 16:34:34
字体:
来源:转载
供稿:网友

UITableViewCell 原生左滑菜单使用

写在前面的

在iOS8以前,tableViewCell的左滑菜单是不能添加多个的,也不能定制颜色和标题,实现左滑的自定义菜单只能用第三方开源库或者自己写,iOS8多了一个方法来自定义菜单,现在就非常简便了。 就是这个

@available(iOS 8.0, *) optional public func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? // supercedes -tableView:titleForDeleteConfirmationButtonForRowAtIndexPath: if return value is non-nil

左滑菜单的需求列表

tableView中左滑出可自定义数量,颜色,标题,事件的菜单。菜单滑出状态下,滚动,或者点击其他区域,tableView需要收回菜单。收回菜单的动画效果。响应事件以后,需要收回菜单,需要支持动画。

代码说明每个需求的实现原理

tableView中左滑出菜单,其实就是开启editing模式

//允许出现左滑菜单, 实现UITableViewDataSource func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { PRint(editingStyle.rawValue) }

自定义数量,颜色,标题,事件

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let cellItem = viewModel.cellItems[indexPath.row] let selectChannelId = cellItem.channelId var mActionArray = [UITableViewRowAction]() let requestHandler = KRChannelRequestHandler.sharedInstance //置顶按钮 let isPin = cellItem.pinTime > 0 ? true : false let pinTitle = isPin ? "取消置顶" : "置顶" let pinAction = UITableViewRowAction(style: .normal, title: pinTitle) { (pinAction, indexPath) in //关闭编辑模式,允许动画 tableView.setEditing(false, animated: true) //置顶处理 } //免打扰按钮 let isDnd = cellItem.dnd == "yes" ? true : false let dndTitle = isDnd ? "取消免打扰" : "免打扰" let dndAction = UITableViewRowAction(style: .normal, title: dndTitle) { (dndAction, indexPath) in //关闭编辑模式 tableView.setEditing(false, animated: true) //免打扰处理 } //自定义按钮颜色 dndAction.backgroundColor = UIColor(hexString: "#FF9C00") //删除按钮 let deleteAction = UITableViewRowAction(style: .destructive, title: "移除") { (deleteAction, indexPath) in //删除处理 } mActionArray = [deleteAction,dndAction,pinAction] return mActionArray }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表