简体   繁体   English

UIFieldBehaviour 用于将动态视图捕捉到屏幕的顶部、底部或中间

[英]UIFieldBehaviour for snapping dynamic view to top, bottom or middle of screen

I'm using a draggable view which is the width and height of the screen and can be moved up or down on the screen depending on the pan gesture.我正在使用一个可拖动视图,它是屏幕的宽度和高度,可以根据平移手势在屏幕上向上或向下移动。

When the pan gesture has ended I want it to snap to three different y positions, top, middle or bottom of the screen according to where the view was when the pan ended.当平移手势结束时,我希望它根据平移结束时视图的位置捕捉​​到三个不同的 y 位置,即屏幕的顶部、中间或底部。 I want something like the UIFieldBehaviour where a force is animating it to the correct position.我想要类似 UIFieldBehaviour 的东西,其中一个力将其动画到正确的位置。

When in top the whole view will be displayed and when in the bottom only like 30px should be displayed and the rest of the view will be under the screen so to speak.当在顶部时,整个视图将被显示,当在底部时,应该只显示 30px,其余的视图将在屏幕下方可以这么说。 Therefore I need the force to only behave to the top 30px of the view.因此,我需要的力仅作用于视图的顶部 30 像素。

Force field behaviour (sorry for bad painting):力场行为(抱歉画不好):

在此处输入图片说明

Snap behaviour:捕捉行为:
在此处输入图片说明

Any ideas on how to achieve this?关于如何实现这一目标的任何想法?

It was easier than I thought.这比我想象的要容易。 I'm using the new UIViewPropertyAnimator and when pan .ended I just check whether the targets y-position should snap to the top, bottom or middle by comparing it to the height of the UIScreen.我正在使用新的 UIViewPropertyAnimator,当 pan .ended 时,我只是通过将目标 y 位置与 UIScreen 的高度进行比较来检查目标 y 位置是否应该捕捉到顶部、底部或中间。

        animator!.addAnimations({
            print(target.frame.origin.y)

            if (target.frame.origin.y > UIScreen.main.bounds.height / 2) {
                if (target.frame.origin.y > (UIScreen.main.bounds.height - 50)) {
                    target.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - 25, width: self.view.frame.width, height: self.view.frame.height)
                } else {
                target.frame = CGRect(x: 0, y: UIScreen.main.bounds.height - 95, width: self.view.frame.width, height: self.view.frame.height)
                }
            } else {
                target.frame = CGRect(x: 0, y: 120, width: self.view.frame.width, height: self.view.frame.height)
            }
        })
        animator!.startAnimation()

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

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