Skip to content

Instantly share code, notes, and snippets.

@CodeSlicing
Created March 27, 2021 08:14
Show Gist options
  • Save CodeSlicing/1dedd9d3a720c5ff81f55b9d83a01502 to your computer and use it in GitHub Desktop.
Save CodeSlicing/1dedd9d3a720c5ff81f55b9d83a01502 to your computer and use it in GitHub Desktop.
Native Source code for CodeSlicing episode on demystifying property wrappers part 1
//
// StateAndBindingDemoNative.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.
//
// Created by Adam Fordyce on 27/03/2021.
// Copyright © 2020 Adam Fordyce. All rights reserved.
//
import SwiftUI
struct StateAndBindingDemoNative: View {
private let _counter = State(initialValue: 0)
private var counter: Int {
_counter.wrappedValue
}
private var _$counter: Binding<Int> {
_counter.projectedValue
}
var body: some View {
VStack(spacing: 50) {
Text("Current count: \(counter)")
.font(.title)
CounterUpdatingButton(counter: _$counter)
}
}
}
private struct CounterUpdatingButton: View {
let counter: Binding<Int>
var body: some View {
VStack {
Button {
counter.wrappedValue += 1
} label: {
Text("Increment")
.font(.title)
.shadow(radius: 2)
.padding()
.background(LinearGradient(
gradient: Gradient(colors: [.red, .orange]),
startPoint: .topLeading,
endPoint: .bottomTrailing))
.clipShape(Capsule())
.overlay(Capsule().stroke(Color.white, lineWidth: 1))
.contentShape(Capsule())
}
}
}
}
struct BindingDemo_Previews: PreviewProvider {
struct BindingDemo_Harness: View {
var body: some View {
StateAndBindingDemoNative()
.frame(maxWidth: .infinity, maxHeight: .infinity)
.foregroundColor(.white)
.background(Color(white: 0.1))
.ignoresSafeArea()
}
}
static var previews: some View {
BindingDemo_Harness()
.previewDevice("iPhone 8")
.previewDisplayName("iPhone 8")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment