TagCloudView.swift 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import SwiftUI
  2. struct TagCloudView: View {
  3. var tags: [String]
  4. @State private var totalHeight
  5. // = CGFloat.zero // << variant for ScrollView/List
  6. = CGFloat.infinity // << variant for VStack
  7. var body: some View {
  8. VStack {
  9. GeometryReader { geometry in
  10. self.generateContent(in: geometry)
  11. }
  12. }
  13. // .frame(height: totalHeight)// << variant for ScrollView/List
  14. .frame(maxHeight: totalHeight) // << variant for VStack
  15. }
  16. private func generateContent(in g: GeometryProxy) -> some View {
  17. var width = CGFloat.zero
  18. var height = CGFloat.zero
  19. return ZStack(alignment: .topLeading) {
  20. ForEach(self.tags, id: \.self) { tag in
  21. self.item(for: tag)
  22. .padding([.horizontal, .vertical], 4)
  23. .alignmentGuide(.leading, computeValue: { d in
  24. if abs(width - d.width) > g.size.width
  25. {
  26. width = 0
  27. height -= d.height
  28. }
  29. let result = width
  30. if tag == self.tags.last! {
  31. width = 0 // last item
  32. } else {
  33. width -= d.width
  34. }
  35. return result
  36. })
  37. .alignmentGuide(.top, computeValue: { _ in
  38. let result = height
  39. if tag == self.tags.last! {
  40. height = 0 // last item
  41. }
  42. return result
  43. })
  44. }
  45. }.background(viewHeightReader($totalHeight))
  46. }
  47. private func item(for text: String) -> some View {
  48. Text(text)
  49. .padding(.all, 5)
  50. .font(.body)
  51. .background(Color.insulin)
  52. .foregroundColor(Color.white)
  53. .cornerRadius(5)
  54. }
  55. private func viewHeightReader(_ binding: Binding<CGFloat>) -> some View {
  56. GeometryReader { geometry -> Color in
  57. let rect = geometry.frame(in: .local)
  58. DispatchQueue.main.async {
  59. binding.wrappedValue = rect.size.height
  60. }
  61. return .clear
  62. }
  63. }
  64. }
  65. struct TestTagCloudView: View {
  66. var body: some View {
  67. VStack {
  68. Text("Header").font(.largeTitle)
  69. TagCloudView(tags: ["Ninetendo", "XBox", "PlayStation", "PlayStation 2", "PlayStation 3", "PlayStation 4"])
  70. Text("Some other text")
  71. Divider()
  72. Text("Some other cloud")
  73. TagCloudView(tags: ["Apple", "Google", "Amazon", "Microsoft", "Oracle", "Facebook"])
  74. }
  75. }
  76. }