Created
January 21, 2021 16:21
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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