【发布时间】:2015-05-19 01:36:22
【问题描述】:
我希望能够通过向左滑动、向右滑动手势在 UIView 的 2 种状态之间进行转换。本质上,我想在用户开始向左滑动时开始扩展视图的高度,并在启动向右滑动时“缩小”它。我可以很容易地使用 CAAnimation 在两种状态之间制作动画,但理想情况下我想要的是控制过渡的手势,而不是给它一个“持续时间”。所以基本上手势的范围被映射到高度的扩展/收缩......我在解释自己方面做得很糟糕,但苹果一直在这样做。
这是我的自定义 UIView 目前的外观:
class CustomUIView: UIView {
@IBOutlet var swipeView: UIView!
var shouldExecuteExpandAnimation:Bool = true;
var shouldExecuteShrinkAnimation:Bool = true;
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSBundle.mainBundle().loadNibNamed("CustomUIView", owner: self, options: nil)
swipeView.backgroundColor = UIColor.grayColor()
self.addSubview(self.swipeView)
}
func performAnimation(fromTransform:CATransform3D, toTransform:CATransform3D, duration:CFTimeInterval) {
var animation:CABasicAnimation = CABasicAnimation(keyPath: "transform")
animation.delegate = self
var transformView = transform
animation.fromValue = NSValue(CATransform3D: fromTransform)
animation.toValue = NSValue(CATransform3D: toTransform)
animation.duration = duration
self.swipeView.layer.addAnimation(animation, forKey: nil)
self.swipeView.layer.transform = toTransform
}
func expandView() {
if shouldExecuteExpandAnimation {
performAnimation(CATransform3DIdentity, toTransform: CATransform3DMakeScale(1, 4, 1), duration: 0.1)
shouldExecuteShrinkAnimation = true;
}
shouldExecuteExpandAnimation = false;
}
func shrinkView() {
if shouldExecuteShrinkAnimation {
performAnimation(CATransform3DMakeScale(1, 4, 1), toTransform: CATransform3DMakeScale(1, 1, 1), duration: 0.1)
shouldExecuteExpandAnimation = true
}
shouldExecuteShrinkAnimation = false;
}
func manageViewWithGesture(gestureRecognizer:UISwipeGestureRecognizer) {
switch gestureRecognizer.direction {
case UISwipeGestureRecognizerDirection.Right:
expandView()
case UISwipeGestureRecognizerDirection.Left:
shrinkView()
default:
break
}
}
}
【问题讨论】:
-
您需要使用平移手势识别器而不是滑动手势识别器。然后,您将在用户移动手指时获得更新。您可以检查
translation.x以确定他们的移动。
标签: ios cocoa-touch swift uiview core-animation