繁体   English   中英

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

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

我希望能够通过向左滑动,向右滑动手势在UIView的2个状态之间进行转换。 本质上,我想在用户开始向左滑动并在开始向右滑动时“缩小”视图时开始扩大视图的高度。 我可以使用CAAnimation轻松地在两个状态之间进行动画处理,但是理想情况下,我想要的是控制过渡的手势,而不是为其赋予“持续时间”。 因此,手势的范围本质上是与高度的扩展/缩小相对应的……我在解释自己方面做得很糟糕,但是Apple一直都这样做。

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

    }

}

正如亚伦所说,您无法通过滑动获得中间值。 什么也没发生,然后触发。 您需要使用平移手势识别器或您自己的自定义手势识别器。 为此,可能更容易解释您从标准的平移手势识别器获得的转换值。

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

您可以调整该方法以使动画在用户拖动平移手势时运行。

查看此链接:

Github上的KeyframeViewAnimations演示项目

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM