0

I am working with UIPanGestureRecognizer right now and I am following THIS tutorial and I am trying to print the velocity of UIView into labels which is in the view.

But it's printing 0.0 every time when I move the view with UIPanGestureRecognizer as shown into below Image:

This is 1st Image where I didn't move UIView

enter image description here

And this is second Image where I move it:

enter image description here

As you can see the labels displays same message at both situations.

Here is my Simple code for this:

import UIKit

class PanViewController: UIViewController {

@IBOutlet weak var testView: UIView!
@IBOutlet weak var horizontalVelocityLabel: UILabel!
@IBOutlet weak var verticalVelocityLabel: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()

    let aSelector : Selector = "moveViewWithGestureRecognizer:"
    let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: aSelector)

    self.testView.addGestureRecognizer(panGestureRecognizer)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

func moveViewWithGestureRecognizer(panGestureRecognizer: UIPanGestureRecognizer){

    var touchLocation : CGPoint = panGestureRecognizer.locationInView(self.view)
    self.testView.center = touchLocation

    var velocity : CGPoint = panGestureRecognizer.velocityInView(self.view)

    // Here is the Problem
    self.horizontalVelocityLabel.text = String(format: "Horizontal Velocity: %.2f points/sec", velocity.x)
    self.verticalVelocityLabel.text = String(format: "Vertical Velocity: %.2f points/sec", velocity.y)
     }
}

I have tried this,this and this but nothing helps me.

Please tell me what I am doing wrong?

Community
  • 1
  • 1
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165

1 Answers1

0

You first need to convert CGFloat to Float

 self.horizontalVelocityLabel.text = String(format: "Horizontal Velocity: %.2f points/sec",Float(velocity.x))
 self.verticalVelocityLabel.text = String(format: "Vertical Velocity: %.2f points/sec",Float(velocity.y))
codester
  • 36,891
  • 10
  • 74
  • 72
  • Thanks for the reply and I have tried something like that before but with this label prints well but `UIView` is not moving as moved before only text labels is changes and when I left the mouse click the view takes that position. – Dharmesh Kheni Dec 09 '14 at 06:21
  • @DharmeshKheni it may be code issue you should post it in another question.But converting `CGFloat` to `Float` will format the lables. You should look your code for that.If you face any problem you can ask me – codester Dec 09 '14 at 06:24
  • @DharmeshKheni that looks like you are main thread issue.As `panGesture` moves it so many times and you are formatting the `Strings` and every time you are updating the lables.You can use counter to update the lables every 10 times call. – codester Dec 09 '14 at 06:36
  • any other easy and simple way to do this? – Dharmesh Kheni Dec 09 '14 at 07:36