Ios 使用动画将UIView移动或捕捉到屏幕的另一侧
我正在使用为我的iOS应用程序制作一个浮动操作按钮。我希望能够拖动这个按钮周围,并有它捕捉到屏幕的另一边,如果用户想移动它的方式。浮动cocoapod已经提供了一种拖动它的方法,我正在尝试修改这个方法,这样按钮就会随着动画捕捉到屏幕的另一个角落(左下角)。到目前为止,我已经做到了:Ios 使用动画将UIView移动或捕捉到屏幕的另一侧,ios,swift,Ios,Swift,我正在使用为我的iOS应用程序制作一个浮动操作按钮。我希望能够拖动这个按钮周围,并有它捕捉到屏幕的另一边,如果用户想移动它的方式。浮动cocoapod已经提供了一种拖动它的方法,我正在尝试修改这个方法,这样按钮就会随着动画捕捉到屏幕的另一个角落(左下角)。到目前为止,我已经做到了: extension UIView { func addDragging(){ let panGesture = UIPanGestureRecognizer(target: self, actio
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 )
}
}
}
扩展UIView{
func addDragging(){
让panGesture=ui panGesture识别器(目标:self,操作:#选择器(draggedAction(:))
self.addgesture识别器(panGesture)
}
@objc专用函数DragedAction(uPan:UIPangestureRecognitor){
让translation=pan.translation(在:self.superview中)
self.center=CGPoint(x:self.center.x+translation.x,y:self.center.y+translation.y)
平移.setTranslation(CGPoint.zero,in:self.superview)
//我自己添加了以下行-不工作
如果让superview=self.superview{
如果self.center.x我自己添加的代码识别出按钮已经移到了屏幕的左侧,但这就是我所能做到的。我只需要让它在用户停止拖动按钮时将自身设置为左下角的动画,然后在用户再次向右移动按钮时将其设置为另一侧。我不确定我是否能用约束做到这一点,因为我没有使用故事板,也不知道cocoapod是如何约束自己的。非常感谢您的帮助 您可以通过将添加的代码替换为以下内容来实现这一点:
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
}
}
}
如果让superview=self.superview{
//案例向左移动
如果self.center.x
要点是建议使用UIView.animate()
函数。根据需要调整参数以获得所需的动画