实现UITableViewCell的左滑自定义View

实现效果

WechatIMG302.png

实现步骤

1. 在 UITableViewCell 中处理

自定义按钮布局

  • 使用 btnView 作为按钮的容器
  • 添加 topBtn(置顶按钮)和 delBtn(删除按钮)到 btnView 中,并设置布局。
lazy var btnView: UIView = {
    let object = UIView()
    object.backgroundColor = .black

    object.addSubview(self.topBtn)
    self.topBtn.snp.makeConstraints { make in
        make.width.equalTo(self.topBtn.width)
        make.left.equalToSuperview().offset(5)
        make.top.bottom.equalToSuperview()
    }

    object.addSubview(self.delBtn)
    self.delBtn.snp.makeConstraints { make in
        make.width.equalTo(self.delBtn.width)
        make.top.bottom.equalToSuperview()
        make.left.equalTo(self.topBtn.snp.right).offset(5)
        make.right.equalToSuperview().offset(-5)
    }

    return object
}()

lazy var topBtn: UILabel = {
    let object = UILabel()
    object.textAlignment = .center
    object.text = "置顶"
    object.width = 65
    return object
}()

lazy var delBtn: UILabel = {
    let object = UILabel()
    object.textAlignment = .center
    object.text = "删除"
    object.width = 65
    return object
}()

添加btnView到cell的contentView右边

contentView.addSubview(self.btnView)

self.btnView.snp.makeConstraints { make in
    make.left.equalTo(contentView.snp.right)
    make.top.bottom.equalToSuperview()
}

2. UITableView中处理

tableView开启编辑

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

添加系统的侧滑样式

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    var actions: [UIContextualAction] = []
    let datas = ["置顶","删除"]
    datas.forEach { item in
        // "              "  占位符,让系统的侧滑View拉伸
        let action = UIContextualAction(style: .destructive, title:  "              ") {(action, view, completionHandler) in
            if indexPath.section >= self.filterDatas.count {
                completionHandler(true)
                return
            }

            if item == "删除"{
                //处理删除逻辑
                self.itemTopClick(indexPath: indexPath)
            }

            if item == "置顶" {
                //处理置顶逻辑
                self.itemDelClick(indexPath: indexPath)
            }

            completionHandler(true)
        }

        //系统侧滑样式背景色
        action.backgroundColor = .black
        actions.append(action)
    }

    let swipeActionsConfiguration = UISwipeActionsConfiguration(actions: actions)

    //侧滑能否无限拉伸
    swipeActionsConfiguration.performsFirstActionWithFullSwipe = false
    return swipeActionsConfiguration
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容