Skip to content

Instantly share code, notes, and snippets.

@colejd
Created January 28, 2022 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colejd/56eccafea177279faa369f2769be11ad to your computer and use it in GitHub Desktop.
Save colejd/56eccafea177279faa369f2769be11ad to your computer and use it in GitHub Desktop.
SwiftUI View that fills space and pins its contents to a given corner
//
// PinningToCorner.swift
// No license, go wild.
//
import SwiftUI
struct PinningToCorner<Content: View>: View {
enum Corner {
case topLeading
case topTrailing
case bottomLeading
case bottomTrailing
}
private let corner: Corner
private let content: Content
init(_ corner: Corner, @ViewBuilder content: () -> Content) {
self.corner = corner
self.content = content()
}
var body: some View {
VStack(spacing: 0) {
if corner == .bottomLeading || corner == .bottomTrailing {
Spacer()
}
HStack(spacing: 0) {
if corner == .topTrailing || corner == .bottomTrailing {
Spacer()
}
content
if corner == .topLeading || corner == .bottomLeading {
Spacer()
}
}
if corner == .topLeading || corner == .topTrailing {
Spacer()
}
}
}
}
struct PinningToCorner_Previews: PreviewProvider {
static var previews: some View {
Group {
PinningToCorner(.topLeading) {
Text("Top-leading")
}
PinningToCorner(.topTrailing) {
Text("Top-trailing")
}
PinningToCorner(.bottomLeading) {
Text("Bottom-leading")
}
PinningToCorner(.bottomTrailing) {
Text("Bottom-trailing")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment