Difference between revisions of "Mobile App Dev 2021W: Tutorial 3"

From Soma-notes
Jump to navigation Jump to search
Line 4: Line 4:


# What is the initial coordinates of the box?  Of the circle?  What are these coordinates relative to?
# What is the initial coordinates of the box?  Of the circle?  What are these coordinates relative to?
#  
# How do you change the drag gesture to be processed "OnEnded" rather than "OnDrag"?  How does this change the behaviour of the program?
#


==Code==
==Code==

Revision as of 02:58, 31 January 2021

This tutorial is still in development.

Tasks

  1. What is the initial coordinates of the box? Of the circle? What are these coordinates relative to?
  2. How do you change the drag gesture to be processed "OnEnded" rather than "OnDrag"? How does this change the behaviour of the program?

Code

drag-demo.zip

//
//  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
    
    var body: some View {
        return Circle()
            .fill(Color.blue)
            .frame(width: 128, height: 128)
            .position(location)
            .gesture(DragGesture()
                        .onChanged { value in
                            self.location = value.location})
    }
}

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()
    }
}