美文网首页iOS学习
Swift自定义TableView左滑删除按钮样式

Swift自定义TableView左滑删除按钮样式

作者: 向日葵的夏天_summer | 来源:发表于2018-11-16 15:52 被阅读349次

    Swift自定义TableView左滑删除按钮样式

    1. 效果图

    1111.png

    2. 实现过程

    在tableView的layoutSubview中遍历,然后可以自定义一个按钮添加上去

    override func layoutSubviews() {
        super.layoutSubviews()
        
        if #available(iOS 11.0, *) {
            for subview in self.subviews where subview.isKind(of: NSClassFromString("UISwipeActionPullView")!) {
                subview.backgroundColor = Main_RedColor
                
                for view in subview.subviews where view.isKind(of: NSClassFromString("UISwipeActionStandardButton")!) {
                    
                    view.backgroundColor = Main_RedColor
    
                    let deleteBtn = setupDeleteBtn(frame: CGRect(x: 0, y: 0, width: autoWidth(width: 160), height: view.height))
                    view.addSubview(deleteBtn)
                    view.bringSubview(toFront: deleteBtn)
                }
            }
            
        } else {    // IOS 10以及以下
            for subview in subviews where subview.isKind(of: NSClassFromString("UITableViewCellDeleteConfirmationView")!) {
                subview.backgroundColor = Main_RedColor
                
                for view in subview.subviews where view.isKind(of: UIButton.self) {
                    view.backgroundColor = Main_RedColor
                    
                    let deleteBtn = setupDeleteBtn(frame: view.frame)
                    view.addSubview(deleteBtn)
                    view.bringSubview(toFront: deleteBtn)
                }
            }
        }
    }
    
    
    private func setupDeleteBtn(frame: CGRect) -> UIButton {
        
        let deleteBtn = UIButton(type: .custom)
        deleteBtn.frame = frame
        deleteBtn.backgroundColor = Main_RedColor
        deleteBtn.setTitle("删除", for: .normal)
        deleteBtn.setTitleColor(UIColor.white, for: .normal)
        deleteBtn.titleLabel?.font = UIFont.systemFont(ofSize: autoFont(size: 32))
        deleteBtn.setImage(UIImage(named: "delete"), for: .normal)
        deleteBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, autoWidth(width: 16))
        return deleteBtn
    }
    

    3. 左滑功能

    //MARK:- 左滑删除
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    
        deleteItemByModel(chapter: chapterModels?[indexPath.row])
     
    }
    

    相关文章

      网友评论

        本文标题:Swift自定义TableView左滑删除按钮样式

        本文链接:https://www.haomeiwen.com/subject/yohmfqtx.html