iOS | UITableView简单实现一种树状展示视图

本例提供了一种“最简单”的利用UITableView实现树状结构的方法和思路,适用于OC和Swift。

最终效果

思路

  • 定义数据模型TreeNode,里边有控制展开/关闭的属性isOpen,以及它的儿子节点subNodes

  • 定义tableView的数据源dataSource = [TreeNode]()

  • 点击cell的时候,操作数据源dataSource插入或移除node.subNodes

  • 点击cell的时候,设置node.isOpen = !node.isOpen

  • 点击cell的时候,根据isOpen来选择插入insertcells还是移除removecells;

  • 针对不同的cellTreeNodeCellTreeLeafCell处理cell的显示;

  • 定义JSON数据模型为如下结构:

[
    {
        "name": "1",
        "subs": [
            {
                "name": "1.1",
                "subs": [
                    {
                        "name": "1.1.1",
                        "subs": []
                    }
                ]
            }
        ]
    }
]
  • 定义数据源模型为如下结构
class TreeNode: NSObject {
    var name = ""
    var isOpen = false
    var subNodes = [TreeNode]()
    var levelString = ""
    
    var level: Int{
        return levelString.components(separatedBy: ".").count
    }
    var needsDisplayNodes: [TreeNode]{
        return needsDisplayNodesOf(ancestor: self)
    }
    var isLeaf: Bool{
        return subNodes.isEmpty
    }
}

实现

  • 点击cell的处理逻辑
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    
    let node = dataSource[indexPath.row]
//1. 点击叶子节点,不再展开/插入
    if node.isLeaf {
        return
    }
    
    node.isOpen = !node.isOpen
    let nodes = node.needsDisplayNodes
    let insertIndex = dataSource.index(of: node)! + 1
//2. 插入subNodes - 展开
    if node.isOpen {
        dataSource.insert(contentsOf: nodes, at: insertIndex)
        tableView.insertRows(at: nodes.map{
            IndexPath(row: dataSource.index(of: $0)!, section: 0)
        }, with: .top)
    }
//3. 移除所有的subNodes - 收起
    else{
        for subNode in nodes {
            guard let index = dataSource.index(of: subNode) else {
                continue
            }
            dataSource.remove(at: index)
            tableView.deleteRows(at: 
                [IndexPath(row: index, section: 0)]
            , with: .bottom)
        }
    }
//4. 刷新当前cell的状态 - 卷/展icon
    tableView.reloadRows(at: [indexPath], with: .none)
}
  • cell显示处理逻辑
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let node = dataSource[indexPath.row]
    let flagText = !node.isLeaf ? (node.isOpen ? "-" : "+") : ""
    
    var cell: UITableViewCell!
//1. 叶子节点cell
    if node.isLeaf {
        cell = tableView.dequeueReusableCell(withIdentifier: "TreeLeafCell", for: indexPath) as! TreeLeafCell
    }
    else{
//2. 正常节点cell
        cell = tableView.dequeueReusableCell(withIdentifier: "TreeNodeCell", for: indexPath) as! TreeNodeCell
    }
    
    cell.textLabel?.text = String(repeating: "    ", 
                                  count: (node.level > 1 ? node.level : 0)) 
        + "\(flagText)  " + node.name
    
    return cell
}
  • TreeNode扩展初始化方法
extension TreeNode{ 
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        if key == "subs", let subs = value as? [[String: Any]]{
            for i in 0..<subs.count {
                let tree = TreeNode.modelWithDictionary(subs[i], levelString: i,parent: levelString)
                subNodes.append(tree)
            }
        }
    }
    
    public static func modelWithDictionary(_ dict: [String: Any], levelString index: Int, parent levelString: String?) -> TreeNode{
        let model = TreeNode()
        model.levelString = levelString != nil ? (levelString! + ".\(index + 1)") : "\(index + 1)"
        model.setValuesForKeys(dict)
        return model
    }
}
  • TreeNode扩展计算当前应该显示的subNodes方法
extension TreeNode{
    var needsDisplayNodes: [TreeNode]{
        return needsDisplayNodesOf(ancestor: self)
    }
    
    // 应该显示的
    private func needsDisplayNodesOf(ancestor: TreeNode) -> [TreeNode]{
        var nodes = [TreeNode]()
        for node in ancestor.subNodes {
            nodes.append(node)
            if node.isOpen {
                nodes.append(contentsOf: needsDisplayNodesOf(ancestor: node))
            }
        }
        return nodes.sorted{ $0.levelString < $1.levelString }
    }
}
  • TreeNode扩展测试JSON数据解析方法
extension TreeNode{
    public static func mockData() -> [TreeNode]{
        var trees = [TreeNode]()
        do{
            let data = try Data(contentsOf: Bundle.main.url(forResource: "tree.json", withExtension: nil)!)
            guard let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [[String: Any]] else{
                return trees
            }
            for i in 0..<jsonArray.count{
                let tree = TreeNode.modelWithDictionary(jsonArray[i], levelString: i, parent: nil)
                trees.append(tree)
            }
        }catch{
            fatalError("JSON数据解析失败")
        }
        return trees
    }
}

优缺点

  • 优点

思路清晰,逻辑简单,代码实现容易;
代码执行效率高;
实现了上次卷展状态记忆;

  • 缺点

代码对Data Model的依赖性较强;
没有实现封装;

GitHub

https://github.com/BackWorld/TreeTableView
如果对你有帮助,别忘了点个❤️并关注下我哦。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,919评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,567评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,316评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,294评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,318评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,245评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,120评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,964评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,376评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,592评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,764评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,460评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,070评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,697评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,846评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,819评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,665评论 2 354

推荐阅读更多精彩内容