博客> Swift 教程之TableView使用05 section的打开与关闭
Swift 教程之TableView使用05 section的打开与关闭
2019-08-20 04:53 评论:0 阅读:357 dapang

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()

收藏
0
sina weixin mail 回到顶部