我有一个圆形视图,并通过以下代码覆盖touchesBegan(touches:, withEvent:)
和touchesMoved(touches:, withEvent:)
。
var deltaAngle = CGFloat(0)
var startTransform: CGAffineTransform?
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
let touchPoint = touches.first!.locationInView(view)
let dx = touchPoint.x - view.center.x
let dy = touchPoint.y - view.center.y
deltaAngle = atan2(dy, dx)
startTransform = arrowPickerView.transform
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
{
let touchPoint = touches.first!.locationInView(view)
let dx = touchPoint.x - view.center.x
let dy = touchPoint.y - view.center.y
let angle = atan2(dy, dx)
let angleDifference = deltaAngle - angle
let transform = CGAffineTransformRotate(startTransform!, -angleDifference)
arrowPickerView.transform = transform
}
我想覆盖touchesEnded(touches:, withEvent:)
来计算速度,让视图自然旋转一点(类似于连续滚动)。我目前保存原始变换并计算delta角度。我该如何实现呢?提前谢谢!
答案 0 :(得分:3)
在下面的示例中,CGAffineTransformRotate取决于:
这会创建一个CGAffineTransformRotate,它会以1(s)的持续时间旋转,以创建动态滚动的感觉,使用UIViewAnimationOptions.CurveEaseOut属性
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touchPointEnd = touches.first!.locationInView(view)
self.dateTouchesEnded = NSDate()
let delay : NSTimeInterval = NSTimeInterval(0)
let timeDelta : Double = self.dateTouchesEnded!.timeIntervalSince1970 - self.dateTouchesStarted!.timeIntervalSince1970
let horizontalDistance : Double = Double(touchPointEnd.x - self.touchPointStart!.x)
let verticalDistance : Double = Double(touchPointEnd.y - self.touchPointStart!.y)
var direction : Double = 1
if (fabs(horizontalDistance) > fabs(verticalDistance)) {
if horizontalDistance > 0 {
direction = -1
}
} else {
if verticalDistance < 0 {
direction = -1
}
}
let rotation : Double = (0.1 / timeDelta < 0.99) ? 0.1 / timeDelta : 0.99
let duration : NSTimeInterval = NSTimeInterval(1)
UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseOut, animations: {
let transform = CGAffineTransformRotate(self.imageView.transform, CGFloat(direction) * CGFloat(rotation) * CGFloat(M_PI))
self.imageView.transform = transform
}, completion: nil)
}
我添加了变量以跟踪触摸的开始和结束时间,并添加了touchesBegan函数的CGPoint位置
var dateTouchesStarted : NSDate?
var dateTouchesEnded : NSDate?
var touchPointStart : CGPoint?
在touchesBegan中我添加了:
self.touchPointStart = touchPoint
如上所述设置变量。