ProposedViewSize.swift 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /// The proposed size for a view. `nil` signifies an unspecified dimension.
  2. public struct ProposedViewSize: Hashable, Sendable {
  3. /// The zero proposal.
  4. public static let zero = Self(0, 0)
  5. /// The infinite proposal.
  6. public static let infinity = Self(.infinity, .infinity)
  7. /// The unspecified/ideal proposal.
  8. public static let unspecified = Self(nil, nil)
  9. /// The proposed width (if any).
  10. public var width: Double?
  11. /// The proposed height (if any).
  12. public var height: Double?
  13. /// The proposal as a concrete view size if both dimensions are specified.
  14. var concrete: ViewSize? {
  15. if let width, let height {
  16. ViewSize(width, height)
  17. } else {
  18. nil
  19. }
  20. }
  21. /// Creates a view size proposal.
  22. public init(_ width: Double?, _ height: Double?) {
  23. self.width = width
  24. self.height = height
  25. }
  26. public init(_ viewSize: ViewSize) {
  27. self.width = viewSize.width
  28. self.height = viewSize.height
  29. }
  30. init(_ vector: SIMD2<Int>) {
  31. self.width = Double(vector.x)
  32. self.height = Double(vector.y)
  33. }
  34. /// Replaces unspecified dimensions of a proposed view size with dimensions
  35. /// from a concrete view size to get a concrete proposal.
  36. public func replacingUnspecifiedDimensions(by size: ViewSize) -> ViewSize {
  37. ViewSize(
  38. width ?? size.width,
  39. height ?? size.height
  40. )
  41. }
  42. /// The component associated with the given orientation.
  43. public subscript(component orientation: Orientation) -> Double? {
  44. get {
  45. switch orientation {
  46. case .horizontal:
  47. width
  48. case .vertical:
  49. height
  50. }
  51. }
  52. set {
  53. switch orientation {
  54. case .horizontal:
  55. width = newValue
  56. case .vertical:
  57. height = newValue
  58. }
  59. }
  60. }
  61. /// The component associated with the given axis.
  62. public subscript(component axis: Axis) -> Double? {
  63. get {
  64. self[component: axis.orientation]
  65. }
  66. set {
  67. self[component: axis.orientation] = newValue
  68. }
  69. }
  70. }