如何使用滑动手势控制 2 个 UIView 状态之间的转换?

How to control the transition between 2 UIView states using a swipe gesture?

我希望能够通过向左轻扫、向右轻扫手势在 UIView 的 2 个状态之间转换。本质上,我想在用户开始向左滑动时开始扩展视图的高度,并在向右滑动时开始扩展视图的高度 "shrink" 。我可以使用 CAAnimation 轻松地在两种状态之间设置动画,但理想情况下我想要的是控制过渡的手势,而不是给它一个 "duration"。所以本质上,手势的范围映射到高度的扩展/收缩......我在解释自己方面做得很糟糕,但苹果一直这样做。

这是我的自定义 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
            }

    }

}

正如 Aaron 所说,您无法通过滑动获得中间值。什么都没有发生,然后它开火了。您需要使用平移手势识别器或您自己的自定义手势识别器。为此,解释您从标准平移手势识别器获得的翻译值可能会更容易。

然后您可以使用这些值手动使动画从头到尾不断变化。我在 github 上有一个项目,可以让您使用滑块从头到尾改变动画。

您可以采用这种方法制作动画 运行 当用户拖动平移手势时。

看看这个 link:

KeyframeViewAnimations demo project on Github