使用动画将UIView移动或捕捉到屏幕的另一侧



我正在使用Floaty Cocoapod为我的iOS应用程序制作一个浮动操作按钮。如果用户想把它移到一边,我希望能够拖动这个按钮,并把它卡到屏幕的另一边。Floaty cocoapod已经有了拖动它的方法,我正在尝试修改这个方法,这样按钮就会随着动画捕捉到屏幕的另一个角落(左下角(。到目前为止,我已经做到了以下几点:

extension UIView {
func addDragging(){

let panGesture = UIPanGestureRecognizer(target: self, action: #selector(draggedAction(_ :)))
self.addGestureRecognizer(panGesture)
}
@objc private func draggedAction(_ pan:UIPanGestureRecognizer){

let translation = pan.translation(in: self.superview)
self.center = CGPoint(x: self.center.x + translation.x, y: self.center.y + translation.y)
pan.setTranslation(CGPoint.zero, in: self.superview)

// Added the following lines myself - not working
if let superview = self.superview {
if self.center.x < superview.frame.size.width / 2 {
//self.transform = CGAffineTransform( translationX: 50, y: 0.0 )
}
}
}

}

我自己添加的代码识别出按钮已经移到了屏幕的左侧,但这是我所能识别的。我只需要让它在用户停止拖动按钮时将自己动画化到左下角,然后如果他们再次将按钮向右移动,则将其动画化到另一侧。我不确定我是否能在有约束的情况下做到这一点,因为我没有使用故事板,也不知道这个茧是如何约束自己的。非常感谢您的帮助!

您可以通过将添加的代码替换为以下内容来实现这一点:

if let superview = self.superview {
// Case to move to the left
if self.center.x < superview.frame.size.width / 2 {
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut) {
self.frame = // Whatever your left frame is
} completion: { (blockCalledAfterAnimationBool) in
// A completion handler if you want it
}
} else { // Move to the right
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut) {
self.frame = // Whatever your right frame is
} completion: { (blockCalledAfterAnimationBool) in
// A completion handler if you want it
}
}
}

要点是建议使用UIView.animate()功能。根据需要调整参数以获得所需的动画。

最新更新