将CGFloat值打印到Label中的问题

时间:2014-12-09 06:00:23

标签: swift

我正在使用UIPanGestureRecognizer,我正在关注THIS教程,我正在尝试将UIView的速度打印到视图中的标签中。

但每当我使用UIPanGestureRecognizer移动视图时,它都会打印0.0,如下图所示:

这是我没有移动UIView

的第一张图片

enter image description here

这是我移动它的第二张图片:

enter image description here

正如您所看到的,标签在两种情况下都显示相同的信息。

这是我的简单代码:

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

我尝过thisthisthis,但没有任何帮助。

请告诉我我做错了什么?

1 个答案:

答案 0 :(得分:0)

首先,您需要将CGFloat转换为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))