Skip to content

Instantly share code, notes, and snippets.

@CodeSlicing
Created December 1, 2021 11:06
Show Gist options
  • Save CodeSlicing/83415540e2c9a1f80eb79695b5d60535 to your computer and use it in GitHub Desktop.
Save CodeSlicing/83415540e2c9a1f80eb79695b5d60535 to your computer and use it in GitHub Desktop.
Source code for CodeSlicing episode exploring overlay / background modifiers vs ZStack - demo-02
//
// OverlayVsZStackDemo02.swift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
// AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright © 2021 Adam Fordyce. All rights reserved.
//
import SwiftUI
import PureSwiftUI
private func Square(_ color: Color, _ sideLength: CGFloat = 100) -> some View {
Rectangle()
.fill(color)
.frame(sideLength)
}
struct OverlayVsStackDemo02: View {
@State private var size = CGSize(0, 0)
var body: some View {
let centerSquare = Square(.yellow)
let bigSquare = Square(.white.opacity(0.5), 200)
let littleSquare = Square(.blue, 50)
VStack {
createPattern {
centerSquare
.background(bigSquare)
.overlay(littleSquare, alignment: .topLeading)
.overlay(littleSquare, alignment: .bottomTrailing)
}
createPattern {
ZStack(alignment: .topLeading) {
bigSquare
.frame(size)
ZStack(alignment: .bottomTrailing) {
centerSquare
.geometryReader { geo in
size = geo.size
}
littleSquare
}
littleSquare
}
.frame(size)
}
}
}
private func createPattern<Content: View>(@ViewBuilder content: () -> Content) -> some View {
let redSquare = Square(.red)
return VStack {
redSquare
HStack {
redSquare
content()
redSquare
}
redSquare
}
}
}
struct OverlayVsStackDemo02_Previews: PreviewProvider {
struct OverlayVsStackDemo02_Harness: View {
var body: some View {
OverlayVsStackDemo02()
.padding(20)
.foregroundColor(.white)
.backgroundColor(.white(0.1))
}
}
static var previews: some View {
OverlayVsStackDemo02_Harness()
.previewSizeThatFits()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment