美文网首页学Swift挣美金
Swift 教程之TableView使用05 section的打

Swift 教程之TableView使用05 section的打

作者: iCloudEnd | 来源:发表于2019-05-06 10:05 被阅读2次

Swift 教程之TableView使用04section的打开与关闭

之前系列课程

效果图

Jietu20190506-095951@2x.jpg Jietu20190506-100006@2x.jpg

1. 配置button

 override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let button = UIButton()
        button.tag = section
        let isOpen = sections[section].open
        button.setTitle(isOpen ? "关闭" : "打开", for: .normal)
        //button.setTitle("close", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.addTarget(self, action: #selector(self.openSection), for: .touchUpInside)
        return button
    }

button.tag = section 存储一下标签
button.setTitle(isOpen ? "关闭" : "打开", for: .normal) 自动设置button标题

2. 自动删除或插入

 @objc fileprivate func openSection(button:UIButton){
        print("button tag:",button.tag)
        let section = button.tag
       
        
        var indexPaths = [IndexPath]()
        for row in sections[section].data.indices {
            let indexPathToDelete = IndexPath(row:row, section: section)
            indexPaths.append(indexPathToDelete)
        }
        
        let isOpen = sections[section].open
        sections[section].open = !isOpen
        
        button.setTitle(isOpen ? "打开" : "关闭", for: .normal)
        
        if isOpen {
            tableView.deleteRows(at: indexPaths, with: .fade)
        } else {
            tableView.insertRows(at: indexPaths, with: .fade)
        }
        
        
    }

不要用reloadData()

相关文章

网友评论

    本文标题:Swift 教程之TableView使用05 section的打

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