Skip to content

Instantly share code, notes, and snippets.

Button(action: {
/// This is only called when the user LIFTS their finger off the button (Touch Up Inside)
print("Pressed!")
}) {
Text("Click me!")
}
struct ContentView: View {
@State var buttonPressed = false
var body: some View {
VStack {
/// support for if-else introduced in Xcode 12
if buttonPressed {
Text("Gas pedal pressed!")
} else {
Text("Press to accelerate!")
.foregroundColor(Color.white)
.padding(10)
.background(Color.gray)
.cornerRadius(6)
.padding(10)
.modifier(TouchDownUpEventModifier(changeState: { (buttonState) in
if buttonState == .pressed {
buttonPressed = true
} else {
Text("Press to accelerate!")
.foregroundColor(Color.white)
.padding(10)
.background(Color.gray)
.cornerRadius(6)
.padding(10)
.modifier(TouchDownUpEventModifier(changeState: { (buttonState) in
if buttonState == .pressed {
buttonPressed = true
} else {
/// we can make the modifier more Swifter by wrapping it in a method...
/// ... then making the method an extension of View, so we can easily add it to any SwiftUI view
public extension View {
func onTouchDownUpEvent(changeState: @escaping (ButtonState) -> Void) -> some View {
modifier(TouchDownUpEventModifier(changeState: changeState))
}
}
Text("Press to accelerate!")
.foregroundColor(Color.white)
.padding(10)
.background(Color.gray)
.cornerRadius(6)
.padding(10)
/// our brand-new, shiny view modifier!
.onTouchDownUpEvent(changeState: { (buttonState) in
if buttonState == .pressed {
buttonPressed = true
@aheze
aheze / iPadSwiftPlaygrounds_PlayAudio_SwiftUI.swift
Last active May 22, 2021 22:46
How to play custom audio on Swift Playgrounds for iPad, using SwiftUI. Replace "slow-spring-board" with the name of your audio file.
import AVFoundation
import SwiftUI
import PlaygroundSupport
struct SwiftUIAudioPlayerView: View {
/// the audio player that will play your audio file. Can't be a local variable.
/// Must be a `@State` property because we need to modify it later
@State var audioPlayer: AVAudioPlayer?
@aheze
aheze / iPadSwiftPlaygrounds_PlayAudio_UIKit.swift
Last active July 7, 2020 03:13
How to play custom audio on Swift Playgrounds for iPad, using UIKit. Replace "slow-spring-board" with the name of your audio file.
import AVFoundation
import SwiftUI
import PlaygroundSupport
class UIKitAudioPlayerView: UIView {
/// the audio player that will play your audio file. Can't be a local variable.
var audioPlayer: AVAudioPlayer?
/// so we only make and connect the button once
import SwiftUI
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
/// your push notification code goes here
return true
}
}
@main
struct HelloWorldApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {