Mobile App Dev 2022W: Tutorial 3: Difference between revisions
Created page with "==Code== [https://homeostasis.scs.carleton.ca/~soma/mad-2022w/code/dragDemo2/ContentView.swift dragDemo2 ContentView.swift] <syntaxhighlight lang="swift" line> // // Conten..." |
|||
Line 1: | Line 1: | ||
==Code== | ==Code== | ||
[https://homeostasis.scs.carleton.ca/~soma/mad-2022w/code/dragDemo2/ContentView.swift dragDemo2 ContentView.swift] | ===[https://homeostasis.scs.carleton.ca/~soma/mad-2022w/code/dragDemo2/ContentView.swift dragDemo2 ContentView.swift]=== | ||
<syntaxhighlight lang="swift" line> | <syntaxhighlight lang="swift" line> |
Revision as of 02:47, 26 January 2022
Code
dragDemo2 ContentView.swift
//
// ContentView.swift
// dragDemo2
//
import SwiftUI
struct ContentView: View {
@State var circleLocation = CGPoint(x: -100, y: -100)
var body: some View {
GeometryReader{geometry in
let w = geometry.size.width
let h = geometry.size.height
let boxLocation = CGPoint(x: w/2, y: h/2)
let boxSize = (w < h ? w : h) / 2
let startLocation = CGPoint(x: w/2, y: h/6)
VStack{
SuccessMsg(location: $circleLocation,
boxLocation: boxLocation)
ZStack{
CenteredBox(location: boxLocation, size: boxSize)
MovableCircle(location: $circleLocation,
size: boxSize * 0.8,
startLocation: startLocation)
}
Text("Width: " + w.description +
", Height: " + h.description)
}
}
}
}
struct CenteredBox: View {
var location: CGPoint
var size: CGFloat
var body: some View {
Rectangle()
.stroke(Color.green, lineWidth: 10)
.frame(width: size, height: size)
.position(location)
}
}
struct MovableCircle: View {
@Binding var location: CGPoint
@State private var isDragging = false
var size: CGFloat
var startLocation: CGPoint
var body: some View {
return Circle()
.fill(Color.blue)
.frame(width: size, height: size)
.position(location.x < 0 ? startLocation : location)
.gesture(DragGesture()
.onChanged { value in
self.location = value.location})
}
}
struct SuccessMsg: View {
@Binding var location: CGPoint
var boxLocation: CGPoint
var body: some View {
if (abs(location.x - boxLocation.x) < 20) &&
(abs(location.y - boxLocation.y) < 20) {
Text("Success!").font(.title).bold()
} else {
Text("Drag the circle into the box").font(.title).bold()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}