Skip to content

Instantly share code, notes, and snippets.

@carson-katri
Created January 21, 2021 16:21
Show Gist options
  • Save carson-katri/0fff154930a9da52aaa2c4a8aa558ebb to your computer and use it in GitHub Desktop.
Save carson-katri/0fff154930a9da52aaa2c4a8aa558ebb to your computer and use it in GitHub Desktop.
Adds an `overlay` to a `View` that aligns the middle of the overlay with the edge of the parent, like a badge.
extension View {
func badge<Badge: View>(_ badge: Badge, alignment: Alignment = .topTrailing) -> some View {
overlay(
badge
.alignmentGuide(.leading, computeValue: splitDimension(\.width))
.alignmentGuide(HorizontalAlignment.center, computeValue: splitDimension(\.width))
.alignmentGuide(.trailing, computeValue: splitDimension(\.width))
.alignmentGuide(.top, computeValue: splitDimension(\.height))
.alignmentGuide(VerticalAlignment.center, computeValue: splitDimension(\.height))
.alignmentGuide(.bottom, computeValue: splitDimension(\.height)),
alignment: alignment
)
}
private func splitDimension(_ axis: KeyPath<ViewDimensions, CGFloat>) -> (ViewDimensions) -> CGFloat {
{ $0[keyPath: axis] / 2 }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment