Mobile App Dev 2021W: Tutorial 3
In this tutorial you will be playing with drag-demo, a simple SwiftUI program where you drag a ball into a box.
Submit your answers by 11:59 PM on Sunday, February 7, 2021 via cuLearn. Please submit a text file following this template. Note that you only need to cite sources that weren't covered in lecture and aren't listed below.
Key Concepts & Resources
For this tutorial, however, you shouldn't need to refer to the documentation below; the code itself should be simple enough to understand and experiment with. However, if you want to learn more, see below.
This code introduces these SwiftUI concepts and mechanisms:
- Shapes, specifically circles and rectangles.
- View positions
- Gestures
- ZStack
A list of key Apple articles on SwiftUI is here. Unfortunately, these articles are incomplete and sometimes ambiguous, so you may want to look at other online resources if you are looking to learn more about SwiftUI. I've found the Hacking with Swift online book to be helpful overall, and Mark Lucking's article on drag and drop is informative. Unfortunately, I've found no online resource that is truly authoritative and complete.
Tasks
- 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?
- Where does the circle have to be to get the success menu? Be precise in terms of coordinates.
- Where is view state being stored? Where is it being used?
- How would you make the lines of the rectangle thinner?
- Can you make it impossible for the ball to enter the square (but allow it to be dragged everywhere else on the screen)?
- Do you see any regular closures here? If so, where are they being used and for what purpose? (Do not consider closures that are actually Views.)
Code
//
// 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()
}
}