Skip to content

Instantly share code, notes, and snippets.

@Dev1an
Created July 28, 2021 06:48
Show Gist options
  • Save Dev1an/10b398708a56d8e08ae95cc653e38cea to your computer and use it in GitHub Desktop.
Save Dev1an/10b398708a56d8e08ae95cc653e38cea to your computer and use it in GitHub Desktop.
Create an overlay, aligning a guide of the reference view to a different guide of the overlaid view.
extension View {
@available(iOS 15.0, macOS 12.0, *)
func overlay<Target: View>(align originAlignment: Alignment, to targetAlignment: Alignment, of target: Target) -> some View {
let hGuide = HorizontalAlignment(Alignment.TwoSided.self)
let vGuide = VerticalAlignment(Alignment.TwoSided.self)
return alignmentGuide(hGuide) {$0[originAlignment.horizontal]}
.alignmentGuide(vGuide) {$0[originAlignment.vertical]}
.overlay(alignment: Alignment(horizontal: hGuide, vertical: vGuide)) {
target
.alignmentGuide(hGuide) {$0[targetAlignment.horizontal]}
.alignmentGuide(vGuide) {$0[targetAlignment.vertical]}
}
}
}
extension Alignment {
enum TwoSided: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat { 0 }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment