Skip to content

Commit

Permalink
fix #37 + getWidth without type erasure, first step for removing type…
Browse files Browse the repository at this point in the history
… erasure completly if even possible
  • Loading branch information
dkk committed Dec 7, 2022
1 parent 9f5f586 commit 1975ea1
Show file tree
Hide file tree
Showing 6 changed files with 214 additions and 105 deletions.
35 changes: 5 additions & 30 deletions Sources/WrappingHStack/ContentManager.swift
@@ -1,42 +1,17 @@
import SwiftUI
import Foundation

/// This class manages content and the calculation of their widths (reusing it).
/// It should be reused whenever possible.
class ContentManager {
enum ViewType {
case any(AnyView)
case newLine

init<V: View>(rawView: V) {
switch rawView {
case is NewLine: self = .newLine
default: self = .any(AnyView(rawView))
}
}
}

let items: [ViewType]
let getWidths: () -> [Double]
lazy var widths: [Double] = {
items.map {
if case let .any(anyView) = $0 {
return Self.getWidth(of: anyView)
} else {
return 0
}
}
getWidths()
}()

init(items: [ViewType]) {
init(items: [ViewType], getWidths: @escaping () -> [Double]) {
self.items = items
}

@inline(__always) private static func getWidth(of anyView: AnyView) -> Double {
#if os(iOS)
let hostingController = UIHostingController(rootView: HStack { anyView })
#else
let hostingController = NSHostingController(rootView: HStack { anyView })
#endif
return hostingController.sizeThatFits(in: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)).width
self.getWidths = getWidths
}

func isVisible(viewIndex: Int) -> Bool {
Expand Down
6 changes: 3 additions & 3 deletions Sources/WrappingHStack/LineManager.swift
Expand Up @@ -5,11 +5,11 @@ import Foundation
class LineManager {
private var contentManager: ContentManager!
private var spacing: WrappingHStack.Spacing!
private var width: CGFloat!
private var width: Double!

lazy var firstItemOfEachLine: [Int] = {
var firstOfEach = [Int]()
var currentWidth: CGFloat = width
var currentWidth: Double = width
for (index, element) in contentManager.items.enumerated() {
switch element {
case .newLine:
Expand All @@ -35,7 +35,7 @@ class LineManager {
width != nil
}

func setup(contentManager: ContentManager, width: CGFloat, spacing: WrappingHStack.Spacing) {
func setup(contentManager: ContentManager, width: Double, spacing: WrappingHStack.Spacing) {
self.contentManager = contentManager
self.width = width
self.spacing = spacing
Expand Down
13 changes: 13 additions & 0 deletions Sources/WrappingHStack/ViewType.swift
@@ -0,0 +1,13 @@
import SwiftUI

enum ViewType {
case any(AnyView)
case newLine

init<V: View>(rawView: V) {
switch rawView {
case is NewLine: self = .newLine
default: self = .any(AnyView(rawView))
}
}
}

0 comments on commit 1975ea1

Please sign in to comment.