UITableViewCell 原生左滑菜单使用

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

左滑菜单的需求列表

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

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

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
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值