【问题标题】:How to control the transition between 2 UIView states using a swipe gesture?如何使用滑动手势控制 2 个 UIView 状态之间的转换?
【发布时间】: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


【解决方案1】:

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

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

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

查看此链接:

KeyframeViewAnimations demo project on Github

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 2014-09-24
    • 2016-10-24
    相关资源
    最近更新 更多