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

From Soma-notes
Jump to navigation Jump to search
(Created page with "==Code== [https://homeostasis.scs.carleton.ca/~soma/mad-2021w/code/drag-demo.zip drag-demo.zip] <syntaxhighlight lang="swift" line> // // ContentView.swift // drag_demo i...")
 
Line 1: Line 1:
'''This tutorial is still in development.'''
==Tasks==
# What is the initial coordinates of the box?  Of the circle?  What are these coordinates relative to?
#
==Code==
==Code==



Revision as of 02:56, 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?

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