Mobile App Dev 2021W: Tutorial 3

From Soma-notes
Revision as of 06:54, 31 January 2021 by Soma (talk | contribs) (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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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