Swift Dev Notes
SedatOnat.devAffiliated with SedatOnat.com
  • 👋Welcome to SedatOnat.dev
  • Learning Path
    • What to Learn?
    • How to Learn?
    • Useful Docs
      • Articles
      • Best Practices
      • Event Notes
        • Kodluyoruz
          • GIT - What is Markdown? How to use it?
        • NS Istanbul
          • Trendyol Super App
        • NS Spain
          • SoundCloud SwiftUI Experiences
        • Patika Events
          • Rust at a Glance
          • Being an IOS Developer
          • Mobil Uygulamamdan Nasıl Gelir Elde Ederim?
          • Tecrübeniz Yoksa Yazılımcı Portfolyosu Var: Peki Nasıl Olacak?
          • Yazılımda trend olan başlıklar nelerdir? Hype teknolojilere kapılmalı mıyım?
          • GitHub Profilinizin Önemi ve Geliştirmeniz İçin Öneriler
          • Patika LaunchPad
          • Özgür Kaya - Yazılım Test/Otomasyon Uzmanı Olmak
          • Türkay Ürkmez
          • Patika Derslerini Bitirsek Yazılımcı Olabilir Miyiz?
          • Performanslı ve Kaliteli Kod Yazmak
          • Yazılım Kariyeri İsteyenler: Nereden Başlamak Gerek?
          • Yazılımcılar dikkat burnout var
          • Yazılım Sektöründe Kariyer Tavsiyeleri
          • Front-End Kariyerine başlangıç
          • Öğrenmeniz gereken iş fırsatları: MNM Teknoloji ile PHP Symphony & Magento
          • Yurtdışı kariyer imkanı
          • Mezunlarımıza soralım: Bootcamp hızlandırmadan işe girmeye giden yolculuk
          • Savunma sektörünce mühendis olmak
          • Everything you need to know about technical interviews at top global companies
          • Java ve Framework 'leri - Akın Kaldıroğlu
          • React Native 'e dair Merak Edilenler
          • FAQs about being an Assistant at Patika
          • Career Journey - From Medical Faculty to Software Development
          • How to make your own game?
          • Altogic ile Backend uygulama geliştirmeyi baştan sonra anlayalım
          • Backend Developer Olmaya karar verdim, peki ya sonra?
          • Bir bilene soralım - .Net Framework 'e İlişkin merak ettikleriniz
          • Bir bilene soralım - Go Developer Olmak
          • Bir bilene soralım - Angular hakkında merak edilenler
          • Bu yaz kodlama konusunda kendime nasıl yatırımlar yapabilirim?
        • Tea-Coffee-Human
          • Where to Start for Coding?
        • Ugur Umutoglu
          • Nasıl Mobile Developer Oldum?
        • Yusuf Demirci
          • Nasıl iOS Developer Olarak İlk İşimi Buldum
          • Amsterdam 'da yazılımcı olmak
          • Nasıl iOS Developer Olurum
      • Insights
      • Job Application Notes
      • Media to use in Apps (Authorized)
      • Q&A
      • Quotes
      • Terminology
  • Before Starting
    • Xcode
      • Folder Attributes
      • Project Transfer
      • Shortcuts
      • Annotation
    • Version Control
      • Xcode Cloud
      • GIT
      • GitHub
      • GitLab
      • BitBucket
      • GitKraken
      • SourceTree
    • Swift
      • Declarative vs Imperative Languages
      • Things to Remember
    • Naming
  • DATABASES
    • Apple Database
      • CloudKit
      • CoreData
        • NSError
        • NSFetchRequest
        • NSManagedObject
        • NSMergePolicy
        • NSPredicate
        • FetchRequest
        • Relationships
        • .hasChanges
      • KeyChain
      • UserDefaults
    • 3rd Party Databases
      • AWS Amplify
      • Firebase
      • JSON
      • MySQL
      • ORM
      • Realm
      • SQL Lite
    • Database Comparison
  • Design Patterns
    • Alternatives
      • Clean Swift
      • MVC
      • MVI
      • MVVM
      • Uber RIB
      • Viper
    • Comparison
  • Model
    • Accessibility
    • Assets
    • Error Debugging
    • File Management
  • CODES
    • Pseudo Code
    • Frameworks
      • Cocoa
      • CodeScanner
      • CoreHaptics
      • CoreImage
      • Foundation
      • LocalAuthentication
      • MapKit
      • ?SwiftDate
      • Swinject
      • SwiftUI
      • UIKit
      • UserNotifications
    • APIs
      • AlamoFire
      • Apple URL Loading System
      • ChatGPT
      • Create ML
      • Wikipedia: Map Coordinates
    • Packages
    • Dependency Managers
      • Carthage
      • CocoaPods
      • SPM - Swift Package Manager
    • Libraries
      • RxSwift
      • KingFischer
      • ?SwiftLint
      • Moya
    • Main Pillars (Protocol, Class, Struct, etc.)
      • Protocols
        • OOP vs POP
        • Codable
        • Comparable
        • Equatable
        • Hashable
        • Identifiable
        • Observable
        • ObservableObject
        • PreviewProvider
        • Shape
        • View
      • Protocol vs Class
      • Classes
        • Adding Initializer to a ChildClass
        • Copying Classes
        • Deinitializer
        • Final Class
        • Override
        • Restart the Inheritance
        • Working with Variables
      • Class vs Struct
      • Structs
      • Functions
      • Closures
        • Closure: Escaping
    • Data Collectors
      • Arrays
        • Stride
      • Dictionaries
      • Enums (Enumerations)
      • Sets
      • Tuples
    • Properties / Data Containers
      • Constants
      • Variables
    • Property Wrappers
      • AppStorage
      • Binding
      • Dynamic Language Lookup
      • Environment
      • EnvironmentObject
      • FocusState
      • MainActor
      • Observed
      • Observed vs. State
      • ObservedObject
      • Published
      • State
      • State vs. StateObject
      • StateObject
    • Optionals
    • Data Types
      • Booleans
      • Date-Time
      • Numbers
      • Strings
      • Type Annotations
    • Operators
    • Conditionals
      • on...
      • Triggers
    • Loops
    • Physical Properties
      • Camera
      • Dynamic Island
      • Gestures
      • Haptics
      • Notifications
      • Sensors
        • Bluetooth
        • Camera
        • FaceID
        • GPS
        • Gyroscope
        • LIDAR
        • Microphone
        • NFC
        • TouchID / FingerPrint
        • WiFi
      • Speakers
    • Other Properties
      • Siri
      • Widgets
    • Code Pool
      • Text Modifiers
        • Adding and/or
        • .autocapitalization(.none)
        • .joined
        • Text Cases
        • TextEditor
        • Text Styles
      • Others
        • AssertionFailure
        • async/await
        • .constant
        • defer
        • .dismiss
        • extensions
        • Filtering
        • ForEach
        • .formatted()
        • init
        • isMultiple(of:)
        • map()
        • .random
        • .randomElement
        • .removeDublicates()
        • Result
        • self
        • .shuffled
        • .sink
        • SortDescriptor
        • Static let
        • Stepper
        • Super.
        • TabView()
        • Timer
  • View
    • Apple HIG
    • Design
      • Pool
      • Tools
    • Image and Graphic
      • CG - Core Graphics
        • CGAffineTransform
        • CGFloat
        • CGPoint
        • CGRect
        • CGSize
        • Path
      • CI - Core Image
        • CIContext
        • CIFilter
        • CIImage
      • Image
        • Image Modifiers...
          • .background
        • GeometryReader
      • NSObject
      • QR Code
    • Page Elements
      • Button
        • PushButton
      • CheckList
      • Confirmation Dialog
      • Context Menu
      • Display Modes
      • Divider
      • Drag and Drop List
      • Form
      • Grid
      • Group
      • GroupBox
      • Keyboard
      • Label
      • LazyView
      • List
        • .listStyle
      • NavigationLink
      • NavigationSplitView
      • NavigationStack
      • NavigationView
      • NavigationView vs NavigationStack
      • OutlineGroup
      • Picker
      • ProgressView()
      • ScrollView
      • Section
      • Shapes
        • Arc
        • Circle
        • Rectangle
      • sheet()
      • Slider
      • Stacks
      • TextField
      • Toggle
      • Toolbar
      • ViewBuilder
      • WindowGroup
    • View Modifiers
      • .alert
      • .alignment
      • .alignmenGuide
      • .animation
      • .blendMode
      • .blur()
      • .clipShape
      • Color
      • .contentShape
      • .disabled
      • .drawingGroup
      • .fill
      • .ignoreSafeArea
      • .inset
      • .isPresented
      • .navigationBarTitleDisplayMode
      • .navigationTitle
      • .overlay
      • .offset
      • .opacity
      • .padding
      • .position
      • .preferredColorScheme
      • .rotation
      • .scaleEffect
      • .searchable
      • stroke and strokeBorder
      • .task
      • .toggle
      • .trailingIcon
      • .transition
    • Reporting
    • Others
      • AsyncImage
      • Switching Views
      • Drawing
  • Solutions
    • Case Solutions
      • Solutions Pool
        • Adding to Favorites
      • Solutions for: Views
        • Solutions for: Button
        • Solutions for: Dark Mode Color Examples
        • Solutions for: Frame Modifier
        • Solutions for: Gooey Effect
        • Solutions for: List
        • Solutions for: Login Screen
        • Solutions for: Other Elements
        • Solutions for: Star Rating
        • Solutions for: Scrolling
        • Solutions for: Theme
    • Sample Project Pool
  • Testing
    • Debugging
      • Debug View Hierarchy (Xcode)
      • Profile your SwiftUI code and identify slow layouts
    • Testing CheckList
    • Unit Test
  • Documentation
    • GitBook
      • GitBook Page Template
      • GitBook Shortcuts
      • GitBook Documentation
    • MarkDown
  • Deploying and Publishing
    • Checklist
    • Deployment Processes
    • Publishing Processes
      • Reasons of Rejection
    • ASO - App Store Optimization
  • Kaizen
    • CI-CD
Powered by GitBook
On this page
  • Overview
  • Subjects
  • Using Gestures
  • Solutions / Examples
  • Dynamic Emoji
  • Sources
  • Videos
  • Articles / Documents
  • See also

Was this helpful?

  1. CODES
  2. Physical Properties

Gestures

PreviousDynamic IslandNextHaptics

Last updated 2 years ago

Was this helpful?

Overview

Subjects

Using Gestures

Tags: #MagnificationGesture #onChanged #RotationGesture #rotationEffect

Magnification

struct ContentView: View {
    @State private var currentAmount = 0.0
    @State private var finalAmount = 1.0

    var body: some View {
        Text("Hello, World!")
            .scaleEffect(finalAmount + currentAmount)
            .gesture(
                MagnificationGesture()
                    .onChanged { amount in
                        currentAmount = amount - 1
                    }
                    .onEnded { amount in
                        finalAmount += currentAmount 
                        currentAmount = 0
                    }
            )
    }
}

Rotation

struct ContentView: View {
    @State private var currentAmount = Angle.zero
    @State private var finalAmount = Angle.zero

    var body: some View {
        Text("Hello, World!")
            .rotationEffect(currentAmount + finalAmount)
            .gesture(
                RotationGesture()
                    .onChanged { angle in
                        currentAmount = angle
                    }
                    .onEnded { angle in
                        finalAmount += currentAmount
                        currentAmount = .zero
                    }
            )
    }
}

Tapping

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, World!")
                .onTapGesture {
                    print("Text tapped")
                }
        }
        .onTapGesture {
            print("VStack tapped")
        }
    }
}

Dragging

Tags: #offset #DragGesture #CGSize #RotationEffect #removal #swipe

Tags: #Swipe #Drag #DifferentiateWithoutColor #xmark #checkmark

For colorblinds you may should use graphics instead of colors. Differentiate Without Color will help on this purpose.

High Priority Gesture

As default, SwiftUI gives priority to child gesture. To overcome that we should define the parent Gesture as a highpriority.

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, World!")
                .onTapGesture {
                    print("Text tapped")
                }
        }
        .highPriorityGesture(
            TapGesture()
                .onEnded { _ in
                    print("VStack tapped")
                }
        )
    }
}

Simultaneous Gesture

Trigers all the gestures at the same time.

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, World!")
                .onTapGesture {
                    print("Text tapped")
                }
        }
        .simultaneousGesture(
            TapGesture()
                .onEnded { _ in
                    print("VStack tapped")
                }
        )
    }
}

Sequential Gestures

First needs to be long pressed, an than it activates the second gesture.

struct ContentView: View {
    // how far the circle has been dragged
    @State private var offset = CGSize.zero

    // whether it is currently being dragged or not
    @State private var isDragging = false

    var body: some View {
        // a drag gesture that updates offset and isDragging as it moves around
        let dragGesture = DragGesture()
            .onChanged { value in offset = value.translation }
            .onEnded { _ in
                withAnimation {
                    offset = .zero
                    isDragging = false
                }
            }

        // a long press gesture that enables isDragging
        let pressGesture = LongPressGesture()
            .onEnded { value in
                withAnimation {
                    isDragging = true
                }
            }

        // a combined gesture that forces the user to long press then drag
        let combined = pressGesture.sequenced(before: dragGesture)

        // a 64x64 circle that scales up when it's dragged, sets its offset to whatever we had back from the drag gesture, and uses our combined gesture
        Circle()
            .fill(.red)
            .frame(width: 64, height: 64)
            .scaleEffect(isDragging ? 1.5 : 1)
            .offset(offset)
            .gesture(combined)
    }
}

Solutions / Examples

Dynamic Emoji

Sources

Videos

Articles / Documents

See also

https://twitter.com/philipcdavis/status/1580211607627390976?s=12&t=PW_LE1rEl7C8W6gcTx0V3g
Hacking with Swift / 100 Days / Day-86 - How to use gestures in SwiftUI
Hacking with Swift / 100 Days / Day-88 - Moving views with DragGesture and offset()
Hacking with Swift / 100 Days / Day-89 - Coloring views as we swipe