Swift Variables in Switch or If statement - ios

I'm trying to learn how to use Swift and I'm just at the beginning. So this code is probably very bad. I can't find some Information about var handling in switch statements.
In the iOS app you can drag a black view (imgView) along the screen. Now if the touch ends, the imgView should animate to a CGPoint which is calculated from the beginning point and end point of the pan gesture.
#objc func handlePan(recognizer: UIPanGestureRecognizer) {
var locationOfBeganTap = CGPoint()
var locationOfEndTap = CGPoint()
let finalDestination = CGPoint(x: (locationOfBeganTap.x + locationOfEndTap.x), y: locationOfBeganTap.y + locationOfEndTap.y)
switch recognizer.state {
case .changed, .began:
locationOfBeganTap = recognizer.location(in: screenView)
print(locationOfBeganTap)
let translation = recognizer.translation(in: self.view)
if let view = recognizer.view {
view.center = CGPoint(x: view.center.x + translation.x, y: view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint.zero, in: self.view)
case .ended:
locationOfEndTap = recognizer.location(in: screenView)
UIView.animate(withDuration: 2.0, animations: {
print(locationOfBeganTap)
self.imgView.center = finalDestination
})
default:
break
}
I want to know why the Variable "locationOfBeginTap" is set correctly on .began but further in the Switch statement, the Variable is set to 0 again. When and why did it change? And How could I avoid that?

It's all about variable scope. This has nothing do with switch or if. Each time handlePan is called, you create new local variables with their initial values.
Move the declaration of those variables to be outside the function so they are actually properties of your class. Then the values will remain between calls to handlePan.

Move you variables outside the method.
var locationOfBeganTap = CGPoint()
var locationOfEndTap = CGPoint()
let finalDestination = CGPoint(x: (locationOfBeganTap.x + locationOfEndTap.x), y: locationOfBeganTap.y + locationOfEndTap.y)
#objc func handlePan(recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .changed, .began:
locationOfBeganTap = recognizer.location(in: screenView)
print(locationOfBeganTap)
let translation = recognizer.translation(in: self.view)
if let view = recognizer.view {
view.center = CGPoint(x: view.center.x + translation.x, y: view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint.zero, in: self.view)
case .ended:
locationOfEndTap = recognizer.location(in: screenView)
UIView.animate(withDuration: 2.0, animations: {
print(locationOfBeganTap)
self.imgView.center = finalDestination
})
default:
break
}
}

Related

Using UIPanGestureRecognizer to swipe down UIView

I have an IBAction for a UIPanGestureRecognizer in my UIView, I am able to handle the gesture and recognise the state changes from began, cancelled and ended, as well as respond to those changes.
However when using the sender.location to handle the swipe down, the UIView actually moves up once the gesture has began, and then continues to move down. The experience is jarring and I am not sure what I am doing wrong. Does anybody have any ideas ?
func update(_ translation: CGPoint, origin: CGPoint) {
let offSetY = translation.y
cardView.frame.origin.y = offSetY
let multiplier = 1 - (translation.y / 2000)
self.view.alpha = multiplier
}
func cancel(_ origin: CGPoint) {
let animator = UIViewPropertyAnimator(duration: 0.6, dampingRatio: 0.6) {
self.visualEffectView.alpha = 1
self.cardView.alpha = 1.0
self.view.alpha = 1.0
self.cardView.center = origin
}
animator.startAnimation()
}
func finish() {
let animator = UIViewPropertyAnimator(duration: 0.9, dampingRatio: 0.9) {
self.visualEffectView.effect = nil
self.dismiss(animated: true, completion: nil)
}
animator.startAnimation()
}
#IBAction func panGestureAction(_ sender: UIPanGestureRecognizer) {
self.view.backgroundColor = .white
let originalCardPosition = cardView.center
//let cardOriginY = cardView.frame.origin.y
let translation = sender.translation(in: self.cardView)
let origin = sender.location(in: self.cardView)
switch sender.state {
case .changed:
if translation.y > 0 { update(translation, origin: origin) }
case .ended:
let translation = sender.translation(in: self.cardView)
if translation.y > 100 {
finish()
} else {
cardView.alpha = 1.0
cancel(originalCardPosition)
}
case .cancelled:
cancel(originalCardPosition)
default: break
}
}
The problem is that you set the origin.y of the cardView directly to the value of translation.y. You need to add translation.y to the view's original y value determined when the gesture begins.
Add a property to the class:
var originalY: CGFloat = 0
Then in the .began state of the gesture, set it:
originalY = cardView.frame.origin.y
Then in your update method you set the origin:
cardView.frame.origin.y = originalY + offSetY

How do I set up an UIPanGestureRecognizer using xib file

func handlePanGesture (panGesture: UIPanGestureRecognizer) {
let translation = panGesture.translation(in: panGesture.view?.superview)
if panGesture.state == .began || panGesture.state == .changed {
panGesture.view?.center = CGPoint(x: (panGesture.view?.center.x)! + translation.x, y: (panGesture.view?.center.y)! + translation.y)
let distance: Double = sqrt(pow((Double(panGesture.view!.center.x) - Double(poin1.x)),2) + pow((Double(panGesture.view!.center.y) - Double(poin1.y)),2))
if distance <= 50{
panGesture.view!.center.x = CGFloat(poin1.x)
panGesture.view!.center.y = CGFloat(poin1.y)
}
panGesture.setTranslation(CGPoint.zero, in: self.view)
}
}
I want custom func handlePanGesture using many points to move in the gesture.

Define actions for subsections of view

I have a view with a circle inside of it controlled by a PanGesture. It is the intention that when a user drags this circle around in the view that some parameters change accordingly.
Here is my viewcontroller:
import UIKit
class ViewController: UIViewController {
var circleCenter: CGPoint!
#IBOutlet weak var soundSpace: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Add a draggable view
let circle = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 50.0, height: 50.0))
circle.center = CGPoint(x: soundSpace.bounds.width/2, y: soundSpace.bounds.height/2) //self.view.center
circle.layer.cornerRadius = 25.0
circle.backgroundColor = UIColor.black
// add pan gesture recognizer to
circle.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(self.dragCircle)))
self.soundSpace.addSubview(circle)
}
func dragCircle(gesture: UIPanGestureRecognizer) {
let target = gesture.view!
switch gesture.state {
case .began, .ended:
circleCenter = target.center
case .changed:
let translation = gesture.translation(in: self.soundSpace)
// Ensure circle stays within subview
if (circleCenter.x + translation.x) > self.soundSpace.bounds.minX+25 &&
(circleCenter.x + translation.x) < self.soundSpace.bounds.maxX-25 &&
(circleCenter.y + translation.y) > self.soundSpace.bounds.minY+25 &&
(circleCenter.y + translation.y) < self.soundSpace.bounds.maxY-25{
target.center = CGPoint(x: circleCenter!.x + translation.x, y: circleCenter!.y + translation.y)
// Check whether circle is in rhs or lhs
if target.center.x < (self.soundSpace.bounds.width / 2){
print("Option 1")
} else {
print("Option 2")
}
}
default: break
}
}
}
I would like to divide my view into subsections. On my x-axis I would like 2 subsections i.e. some parameter change when circle is on the lhs. of the view and same parameters change when circle is on the right hand side of the view. This has already been done (in the only manner I could think of on the top of my head).
Now I would like to divide my y-axis into 9 subsections. I could use an if-statement, but that seems a bit unclean to me. Is there any effective and more elegant way of doing that?
Looking forward to any suggestions, thanks!
To check the correct section of y
func dragCircle(gesture: UIPanGestureRecognizer) {
let target = gesture.view!
switch gesture.state {
case .began, .ended:
circleCenter = target.center
case .changed:
let translation = gesture.translation(in: self.soundSpace)
// Ensure circle stays within subview
if (circleCenter.x + translation.x) > self.soundSpace.bounds.minX+25 &&
(circleCenter.x + translation.x) < self.soundSpace.bounds.maxX-25 &&
(circleCenter.y + translation.y) > self.soundSpace.bounds.minY+25 &&
(circleCenter.y + translation.y) < self.soundSpace.bounds.maxY-25{
target.center = CGPoint(x: circleCenter!.x + translation.x, y: circleCenter!.y + translation.y)
//------ y calculation ------
let yPosition = target.center.y
let totalHeight = self.soundSpace.bounds.height
let totalYSections = 9
let ySectionHeight = totalHeight/totalYSections
let reminder = yPosition % ySectionHeight
let correction = 0
if (reminder > 0) {
correction = 1
}
let currentYSection = (yPosition / ySectionHeight) + correction
print(currentYSection)
//------ y calculation ------
// Check whether circle is in rhs or lhs
if target.center.x < (self.soundSpace.bounds.width / 2){
print("Option 1")
} else {
print("Option 2")
}
}
default: break
}
}
}

UIKit Dynamics with pan, rotate and pinch gesture

I have added UIDynamics to imageview and used pan gesture for that. It is working fine with pan gesture but when I apply pinch gesture with that it is not working. It is showing large imageview but when I start dragging then it is changed to original size.
Here is my code:
func handleAttachmentGesture(_ sender: UIPanGestureRecognizer) {
let location = sender.location(in: emojiSuperView!)
let boxLocation = sender.location(in: self)
switch sender.state {
case .began:
print("Your touch start position is \(location)")
print("Start location in image is \(boxLocation)")
animator.removeAllBehaviors()
let centerOffset = UIOffset(horizontal: boxLocation.x - self.bounds.midX, vertical: boxLocation.y - self.bounds.midY)
attachmentBehavior = UIAttachmentBehavior(item: self, offsetFromCenter: centerOffset, attachedToAnchor: location)
animator.addBehavior(attachmentBehavior)
case .ended:
print("Your touch end position is \(location)")
print("End location in image is \(boxLocation)")
animator.removeAllBehaviors()
// 1
let velocity = sender.velocity(in: emojiSuperView!)
let magnitude = sqrt((velocity.x * velocity.x) + (velocity.y * velocity.y))
if magnitude > ThrowingThreshold {
// 2
let pushBehavior = UIPushBehavior(items: [self], mode: .instantaneous)
pushBehavior.pushDirection = CGVector(dx: velocity.x / 10, dy: velocity.y / 10)
pushBehavior.magnitude = magnitude / ThrowingVelocityPadding
self.pushBehavior = pushBehavior
animator.addBehavior(pushBehavior)
// 3
let angle = Int(arc4random_uniform(20)) - 10
itemBehavior = UIDynamicItemBehavior(items: [self])
itemBehavior.friction = 0.2
itemBehavior.allowsRotation = true
itemBehavior.addAngularVelocity(CGFloat(angle), for: self)
animator.addBehavior(itemBehavior)
}
default:
attachmentBehavior.anchorPoint = sender.location(in: emojiSuperView!)
break
}
}
func recognizePinchGesture(sender: UIPinchGestureRecognizer)
{
weak var dynamicItem: UIDynamicItem?
// whatever your item is, probably a UIView
dynamicItem = self
let behavior = UIGravityBehavior(items: [dynamicItem!])
let animator = UIDynamicAnimator(referenceView: emojiSuperView!)
// or however you're getting your animator
animator.addBehavior(behavior)
sender.view!.transform = sender.view!.transform.scaledBy(x: sender.scale, y: sender.scale)
animator.updateItem(usingCurrentState: self)
self.animator.updateItem(usingCurrentState: self)
sender.scale = 1
}
When a user does any transform event, save current transform to a global variable.
after that when panning start assigns new transform in began state using UIAttachmentBehavior's action property.
attachmentBehavior.action = {
self.attachmentBehavior.items[0].transform = self.aTransform
}

Rotating ImageView using UIPanGestureRecognizer- Swift 3

I am trying to rotate an ImageView I have depending on the X coordinate it is on. Basically, I want it to have a rotation of 0º when x = 300 and a rotation of 180º when x = 190.
I had to program the UIPanGestureRecognizer programmatically. Here is the code I currently have right now:
#objc func personDrag(recognizer: UIPanGestureRecognizer) {
let rotationSub: CGFloat = 1
let translation = recognizer.translation(in: rView)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x, y:view.center.y + translation.y)
view.transform = view.transform.rotated(by: CGFloat.pi - rotationSub)
}
recognizer.setTranslation(CGPoint.zero, in: rView)
}
I was going to attempt to change the rotation degree by 1 every time they panned but it doesn't really work/make sense. Any help would be appreciated. Thank you so much!
Cheers, Theo
You can build your implementation on this:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var imageview: UIImageView!
private var currentRotation: Rotation = .none
/* Certain rotation points (rotation of 0º when x = 300 and a rotation of 180º when x = 190) */
enum Rotation {
case none, xPoint190, xPoint300
}
override func viewDidLoad() {
super.viewDidLoad()
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
imageview.addGestureRecognizer(gestureRecognizer)
imageview.isUserInteractionEnabled = true
}
#IBAction func handlePan(_ gestureRecognizer: UIPanGestureRecognizer) {
guard gestureRecognizer.state == .began || gestureRecognizer.state == .changed else {
return
}
guard let imgView = gestureRecognizer.view else {
return
}
let translation = gestureRecognizer.translation(in: self.view)
imgView.center = CGPoint(x: imgView.center.x + translation.x, y: imgView.center.y + translation.y)
gestureRecognizer.setTranslation(CGPoint.zero, in: self.view)
let angle: CGFloat = self.degreesToRadians(180.0)
/* After reaching x point case - rotating and setting rotation occured to prohibit further rotation */
if imgView.layer.frame.origin.x <= 190, currentRotation != .xPoint190 {
imgView.transform = imgView.transform.rotated(by: angle)
currentRotation = .xPoint190
} else if imgView.layer.frame.origin.x >= 300, currentRotation != .xPoint300 {
imgView.transform = imgView.transform.rotated(by: angle)
currentRotation = .xPoint300
}
private func degreesToRadians(_ deg: CGFloat) -> CGFloat {
return deg * CGFloat.pi / 180
}
}
I hope this will help you.
#objc func rotateViewPanGesture(_ recognizer: UIPanGestureRecognizer) {
touchLocation = recognizer.location(in: superview)
let center = CGRectGetCenter(frame)
switch recognizer.state {
case .began:
deltaAngle = atan2(touchLocation!.y - center.y, touchLocation!.x - center.x) - CGAffineTrasformGetAngle(transform)
initialBounds = bounds
initialDistance = CGpointGetDistance(center, point2: touchLocation!)
case .changed:
let ang = atan2(touchLocation!.y - center.y, touchLocation!.x - center.x)
let angleDiff = deltaAngle! - ang
let a = transform.a
let b = transform.b
let c = transform.c
let d = transform.d
let sx = sqrt(a * a + b * b)
let sy = sqrt(c * c + d * d)
let currentScale = CGPoint(x: sx, y: sy)
let scale = CGAffineTransform(scaleX: currentScale.x, y: currentScale.y)
self.transform = scale.rotated(by: -angleDiff)
layoutIfNeeded()
case .ended:
print("end gesture status")
default:break
}
}
Using Swift5
Programmatically
Rotate view by single point touch
import UIKit
class ViewController: UIViewController {
//Variable for rotating
private var deltaAngle:CGFloat = 0
let squareView : UIView = {
let anyView = UIView()
anyView.backgroundColor = .red
anyView.isUserInteractionEnabled = true
anyView.isMultipleTouchEnabled = true
return anyView
}()
let rotateButton : UIButton = {
let button = UIButton()
button.backgroundColor = .black
button.setImage(UIImage(systemName: "rotate.right"), for: .normal)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
squareView.frame = CGRect(x: 50, y: 50, width: 100, height: 100)
rotateButton.frame = CGRect(x: 0, y: squareView.frame.height-30, width: 30, height: 30)
squareView.center = view.center
view.addSubview(squareView)
squareView.addSubview(rotateButton)
let PanToRotate = UIPanGestureRecognizer(target: self, action: #selector(handleRotateGesture(_:)))
rotateButton.addGestureRecognizer(PanToRotate)
}
#objc func handleRotateGesture(_ recognizer : UIPanGestureRecognizer){
let touchLocation = recognizer.location(in: squareView.superview)
let center = squareView.center
switch recognizer.state{
case .began :
self.deltaAngle = atan2(touchLocation.y - center.y, touchLocation.x - center.x) - atan2(squareView.transform.b, squareView.transform.a)
case .changed:
let angle = atan2(touchLocation.y - center.y, touchLocation.x - center.x)
let angleDiff = self.deltaAngle - angle
squareView.transform = CGAffineTransform(rotationAngle: -angleDiff)
default: break
}
}
}

Resources