简体   繁体   中英

Moving or snapping a UIView to other side of screen with animation

I'm using the Floaty Cocoapod to make a floating action button for my iOS app. I'd like to be able to drag this button around and have it snap to the other side of the screen if the user would like to move it out of the way. The Floaty cocoapod already comes with a way to drag it, and I'm trying to modify this method so that the button will snap with animation to the opposite corner of the screen (lower left). Here is where I've got so far:

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 )
        }
    }
}

}

The code I have added myself recognises the button has been moved over to the left side of the screen, but that's as far as I've got. I just need to get it to animate itself into the lower left corner when the user stops dragging the button, and then to the other side if they move it to the right again. I'm not sure if I can do this with constraints, as I'm not using storyboards and have no idea how this cocoapod constrains itself. Very grateful for any help!

You can accomplish this by replacing your added code with something like:

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
        }
    }
}

Main point is recommended use of the UIView.animate() function. Adjust the parameters as necessary to get the animation you desire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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