Mobile App Dev 2021W: Tutorial 3

From Soma-notes
Revision as of 03:02, 31 January 2021 by Soma (talk | contribs) (→‎Tasks)
Jump to navigation Jump to search

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?
  3. Where does the circle have to be to get the success menu? Be precise in terms of coordinates.
  4. Where is view state being stored? Where is it being used?
  5. How would you make the lines of the rectangle thinner?
  6. Can you make it impossible for the ball to enter the square (but allow it to be dragged everywhere else on the screen)?

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