Skip to content

Commit 67459d0

Browse files
committed
Add support for slicing from directional edges
Currently slicing uses min/max x/y definitions for specifying edges. Adding an API for specifying leading/trailing edges (as well as top/bottom for convenience) makes layout easier for apps that support both LTR and RTL layout.
1 parent 420dc31 commit 67459d0

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

Paralayout/GeometryAdditions.swift

+34-2
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,13 @@ extension CGSize {
9191

9292
// MARK: -
9393

94+
public enum DirectionalEdge {
95+
case top
96+
case bottom
97+
case leading
98+
case trailing
99+
}
100+
94101
extension CGRect {
95102

96103
/// Initialize a CGRect with bounding coordinates (always with non-negative size).
@@ -141,10 +148,35 @@ extension CGRect {
141148
public func offset(by offset: UIOffset) -> CGRect {
142149
return CGRect(origin: origin.offset(by: offset), size: size)
143150
}
144-
151+
152+
/// Divides the receiver in two.
153+
///
154+
/// - parameter edge: The edge from which the amount is interpreted.
155+
/// - parameter amount: The size of the slice (absolute).
156+
/// - returns: A tuple (slice: A rect with a width/height of the `amount`, remainder: A rect with a width/height of
157+
/// the receiver reduced by `amount`).
158+
public func slice(
159+
from edge: DirectionalEdge,
160+
amount: CGFloat,
161+
in layoutDirectionProvider: LayoutDirectionProviding
162+
) -> (slice: CGRect, remainder: CGRect) {
163+
switch (edge, layoutDirectionProvider.effectiveUserInterfaceLayoutDirection) {
164+
case (.top, _):
165+
slice(from: .minYEdge, amount: amount)
166+
case (.bottom, _):
167+
slice(from: .maxYEdge, amount: amount)
168+
case (.leading, .leftToRight), (.trailing, .rightToLeft):
169+
slice(from: .minXEdge, amount: amount)
170+
case (.trailing, .leftToRight), (.leading, .rightToLeft):
171+
slice(from: .maxXEdge, amount: amount)
172+
@unknown default:
173+
fatalError("Unknown user interface layout direction")
174+
}
175+
}
176+
145177
/// Divides the receiver in two.
146178
///
147-
/// - parameter from: The edge from which the amount is interpreted.
179+
/// - parameter edge: The edge from which the amount is interpreted.
148180
/// - parameter amount: The size of the slice (absolute).
149181
/// - returns: A tuple (slice: A rect with a width/height of the `amount`, remainder: A rect with a width/height of
150182
/// the receiver reduced by `amount`).

0 commit comments

Comments
 (0)