iOS cell自定义左滑删除按钮

左滑删除是系统提供的一个非常炫酷的功能,但是UI确实不敢恭维啊,就是太硬了感觉,不太符合审美需求啊。
先看成品:传送门

成品图

解题思路:

1.想要修改它,那就先找到它
2.根据自己的需求修改它 
3.运行看效果

1.找到它

Xcode 查看UI布局图

注解:(条件:Xcode 11.4 /iOS 13.4 模拟器)通过上图,我们会发现TableViewCell 被 _UITableViewCellSwipeContainerView 这个view 包装了,这个view 是和其他的 Cell 是同等级的,这是我们要找的第一层,以此类推。
所以我们得出的层级是:
第一层:_UITableViewCellSwipeContainerView
第二层:UISwipeActionPullView
第三层:UISwipeActionStandardButton (也就是我们要找的)
⚠️重要:从UI中是找到它了,然后从运行的代码中去哪里找到它?最容易让人想到的就是谁触发了它,就应该在哪里找吧。

//MARK: 滑动删除
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        DispatchQueue.main.async {
            let cell = tableView.cellForRow(at: indexPath)
            if cell != nil {
                let subContentView: UIView = (cell?.viewWithTag(1001)!)!
                subContentView.layer.cornerRadius = 0
            }
            
            #warning("这里是主要代码")
            for av in tableView.subviews {
                let avCls = type(of: av)
                if NSStringFromClass(avCls) == "_UITableViewCellSwipeContainerView" {//找到第一层
                    av.layer.cornerRadius = 10
                    for bv in av.subviews {
                        if NSStringFromClass(type(of: bv)) == "UISwipeActionPullView" {//找到第二层
                            for cv in bv.subviews {
                                if NSStringFromClass(type(of: cv)) == "UISwipeActionStandardButton" {//找到第三层
                                    NSLog("cv = \(cv)")
                                    let swipeButton: UIButton = cv as! UIButton
                                    swipeButton.setTitle("啦啦", for: .normal)
                                    swipeButton.setImage(UIImage(named: "icon_delete"), for: .normal)
                                    swipeButton.backgroundColor = UIColor.blue
                                    let cH = bv.frame.size.height
                                    swipeButton.frame = CGRect(x: 0, y: 6, width: cv.frame.size.width, height: cH - 12)
                                    swipeButton.layer.cornerRadius = 5
                                    swipeButton.layer.masksToBounds = true
                                }
                            }
                        }
                    }
                }
            }
        }
        return true
    }

感谢您的阅读!如果您有更好的思路,请您不惜指教一二,感谢您的留言🙏

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

相关阅读更多精彩内容

友情链接更多精彩内容