Created
December 18, 2024 21:48
-
-
Save uy/136d26e70c0efbabe50bc2bd532fe77b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// TreeView.swift | |
// ---------------- | |
// | |
// Created by Utku Yeğen on 19.12.2024. | |
// | |
import SwiftUI | |
struct TreeBranch { | |
let id: UUID = .init() | |
let title: String | |
let leafs: [TreeBranch] | |
} | |
struct TreeView: View { | |
let id: UUID = .init() | |
let tree: [TreeBranch] = [ | |
.init(title: "Tree 1", leafs: [ | |
.init(title: "Leaf 1", leafs: [ | |
.init(title: "Leaf 1.1", leafs: [ | |
.init(title: "Leaf 1.1.1", leafs: []), | |
.init(title: "Leaf 1.1.2", leafs: []), | |
.init(title: "Leaf 1.1.3", leafs: []), | |
.init(title: "Leaf 1.1.4", leafs: []) | |
]) | |
]), | |
.init(title: "Leaf 2", leafs: []), | |
.init(title: "Leaf 3", leafs: []), | |
.init(title: "Leaf 4", leafs: []), | |
.init(title: "Leaf 5", leafs: []) | |
]), | |
.init(title: "Tree 2", leafs: []), | |
.init(title: "Tree 3", leafs: [ | |
.init(title: "Leaf 3", leafs: []), | |
.init(title: "Leaf 4", leafs: []), | |
.init(title: "Leaf 5", leafs: []) | |
]), | |
.init(title: "Tree 4", leafs: []) | |
] | |
var body: some View { | |
ScrollView { | |
ForEach(tree, id: \.id) { branch in | |
TreeRow(branch: branch, depth: 0) | |
} | |
.padding(.horizontal, 16) | |
} | |
} | |
} | |
struct TreeRow: View { | |
let branch: TreeBranch | |
let depth: Int | |
var body: some View { | |
VStack { | |
VStack { | |
HStack { | |
Text(branch.title) | |
Spacer() | |
Text("\(depth)") | |
} | |
.padding(.leading, CGFloat(depth) * 10) | |
buildSeperator() | |
if !branch.leafs.isEmpty { | |
ForEach(branch.leafs, id: \.id) { leaf in | |
TreeRow(branch: leaf, depth: depth + 1) | |
} | |
} | |
} | |
.padding(.vertical, 8) | |
} | |
} | |
@ViewBuilder | |
private func buildSeperator() -> some View { | |
Rectangle() | |
.frame(height: 1) | |
} | |
} | |
#Preview { | |
TreeView() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment