1
0

Alignment.swift 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /// The 2D alignment of a view.
  2. public struct Alignment: Hashable, Sendable {
  3. /// Centered in both dimensions.
  4. public static let center = Self(horizontal: .center, vertical: .center)
  5. /// Touching the top and leading edges.
  6. public static let topLeading = Self(horizontal: .leading, vertical: .top)
  7. /// Centered along the top edge.
  8. public static let top = Self(horizontal: .center, vertical: .top)
  9. /// Touching the top and trailing edges.
  10. public static let topTrailing = Self(horizontal: .trailing, vertical: .top)
  11. /// Touching the bottom and leading edges.
  12. public static let bottomLeading = Self(horizontal: .leading, vertical: .bottom)
  13. /// Centered along the bottom edge.
  14. public static let bottom = Self(horizontal: .center, vertical: .bottom)
  15. /// Touching the bottom and trailing edges.
  16. public static let bottomTrailing = Self(horizontal: .trailing, vertical: .bottom)
  17. /// Centered along the leading edge.
  18. public static let leading = Self(horizontal: .leading, vertical: .center)
  19. /// Centered along the trailing edge.
  20. public static let trailing = Self(horizontal: .trailing, vertical: .center)
  21. /// The horizontal alignment component.
  22. public var horizontal: HorizontalAlignment
  23. /// The vertical alignment component.
  24. public var vertical: VerticalAlignment
  25. /// Creates a custom alignment with the given horizontal and vertical
  26. /// components.
  27. ///
  28. /// - Parameters:
  29. /// - horizontal: The horizontal alignment component.
  30. /// - vertical: The vertical alignment component.
  31. public init(horizontal: HorizontalAlignment, vertical: VerticalAlignment) {
  32. self.horizontal = horizontal
  33. self.vertical = vertical
  34. }
  35. /// Computes the position of a child in a parent view using the provided
  36. /// sizes.
  37. ///
  38. /// - Parameters:
  39. /// - child: The size of the child, as a width/height vector.
  40. /// - parent: The size of the parent, as a width/height vector.
  41. /// - Returns: The position of the child within the parent, as an x/y
  42. /// vector.
  43. public func position(
  44. ofChild child: SIMD2<Int>,
  45. in parent: SIMD2<Int>
  46. ) -> SIMD2<Int> {
  47. let x =
  48. switch horizontal {
  49. case .leading:
  50. 0
  51. case .center:
  52. (parent.x - child.x) / 2
  53. case .trailing:
  54. parent.x - child.x
  55. }
  56. let y =
  57. switch vertical {
  58. case .top:
  59. 0
  60. case .center:
  61. (parent.y - child.y) / 2
  62. case .bottom:
  63. parent.y - child.y
  64. }
  65. return SIMD2(x, y)
  66. }
  67. }