Skip to content

Instantly share code, notes, and snippets.

@Inncoder
Created December 6, 2020 11:19
Show Gist options
  • Save Inncoder/2fe6025b2de98d83427e3da23b8e3f37 to your computer and use it in GitHub Desktop.
Save Inncoder/2fe6025b2de98d83427e3da23b8e3f37 to your computer and use it in GitHub Desktop.
Toggle button
// Created by Inncoder.
// Copyright © 2020 Inncoder AS. All rights reserved.
//
import SwiftUI
struct Button: View {
@State private var buttonSize: CGFloat = 0
@State private var buttonOffset: CGFloat = 0
@State private var buttonColor: Color = .gray
@State private var toggled: Bool = false
var body: some View {
ZStack {
offWhite.edgesIgnoringSafeArea(.all)
Capsule()
.frame(width: capsuleSize, height: capsuleSize / 2)
.foregroundColor(buttonColor)
.shadow(color: Color.black.opacity(0.4), radius: 10, x: 10, y: 10)
.shadow(color: Color.white.opacity(0.9), radius: 10, x: -5, y: -5)
ZStack{
Capsule()
.frame(width: buttonSize, height: (capsuleSize / 2) * 0.85)
.foregroundColor(offWhite)
.offset(x: buttonOffset)
Capsule()
.stroke(offWhite, lineWidth: 3)
.shadow(color: Color.black.opacity(0.3), radius: 4, x: 4, y: 4)
.clipShape(
Capsule()
)
.shadow(color: Color.white.opacity(0.8), radius: 4, x: -5, y: -5)
.clipShape(
Capsule()
)
.frame(width: buttonSize, height: (capsuleSize / 2) * 0.85)
.foregroundColor(offWhite)
.offset(x: buttonOffset)
}
.onTapGesture {
toggleButton()
}
}
.onAppear {
buttonSize = (capsuleSize / 2) * 0.85
buttonOffset = -capsuleSize / 4
}
}
//MARK: - Drawing constants
let capsuleSize: CGFloat = 250
let offWhite = Color(red: 225 / 255, green: 225 / 255, blue: 235 / 255)
//MARK: - Functions
func toggleButton() {
if toggled {
withAnimation(Animation.easeInOut(duration: 0.5)) {
buttonSize = capsuleSize * 0.925
buttonOffset = 0
buttonColor = .gray
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
withAnimation(Animation.easeInOut(duration: 0.5)) {
buttonSize = (capsuleSize / 2) * 0.85
buttonOffset = -capsuleSize / 4
}
}
toggled.toggle()
} else {
withAnimation(Animation.easeInOut(duration: 0.5)) {
buttonSize = capsuleSize * 0.925
buttonOffset = 0
buttonColor = .green
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
withAnimation(Animation.easeInOut(duration: 0.5)) {
buttonSize = (capsuleSize / 2) * 0.85
buttonOffset = capsuleSize / 4
}
}
toggled.toggle()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment