Mobile App Development 2021W Lecture 8

From Soma-notes
Jump to navigation Jump to search

Video

Video from the lecture given on February 3, 2021 is now available.

Code

Below is the modified version of drag-demo that was created in class.

//
//  ContentView.swift
//  drag_demo

import SwiftUI

let boxLocation = CGPoint(x: 200, y: 400)

struct ContentView: View {
    @State var location = CGPoint(x: 185, y: 100)
    var body: some View {
        VStack{
            SuccessMsg(location: $location)
            ZStack{
                Rectangle()
                    .stroke(Color.green, lineWidth: 10)
                    .frame(width: 200, height: 200)
                    .position(boxLocation)
                MovableCircle(location: $location)
            }
        }
    }
}

struct MovableCircle: View {
    @Binding var location: CGPoint
    @State private var isDragging = false
    @State var myColor = Color.blue
    
    var body: some View {
 
        return Circle()
            .fill(myColor)
            .frame(width: isDragging ? 64 : 128, height: isDragging ? 64 : 128)
            .position(location)
            .gesture(DragGesture()
                        .onChanged { value in
                            isDragging = true
                            self.location = value.location
                            }
                        .onEnded { value in
                            isDragging = false
                            self.location = value.location
                            self.location.x += 50
                        }
            )
            .onTapGesture(count: 2, perform: {
                print("Circle clicked!")
                self.myColor = Color.blue
            })
            .onTapGesture(count: 1, perform: {
                print("Circle clicked!")
                self.myColor = Color.red
            })
    }
}

struct SuccessMsg: View {
    @Binding var location: CGPoint
    
    var body: some View {
        if (abs(location.x - boxLocation.x) < 20) &&
            (abs(location.y - boxLocation.y) < 20) {
            Text("Success!").bold()
        } else {
            Text("Drag the circle into the box").bold()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}