0

I'm trying to add Swipe to right and left to collection view cell to transform the container to the right and left with a certain angle

Here is my initial setup

   private func setupGestures() {
        let swipeToRight = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeRight))
        swipeToRight.direction = .right
        container.addGestureRecognizer(swipeToRight)
        
        let swipeToLeft = UISwipeGestureRecognizer(target: self, action: #selector(respondToSwipeLeft))
        swipeToLeft.direction = .left
        container.addGestureRecognizer(swipeToLeft)
        
    }
    
    @objc func respondToSwipeRight(gesture: UIGestureRecognizer) {
        
        let angle = CGFloat(Double.pi/2)
        
        UIView.animate(withDuration: 0.5) {
            self.container.transform = CGAffineTransform(rotationAngle: angle)
        }
    }
    
    
    @objc func respondToSwipeLeft(gesture: UIGestureRecognizer) {
        
        let angle = -CGFloat(Double.pi/2)
        
        UIView.animate(withDuration: 0.5) {
            self.container.transform = CGAffineTransform(rotationAngle: angle)
        }
    }



But it completely rotate the container, which is I don't want, I want to make it something like it, and turn back to it's initial position after a sec or two

[![how it should transform][1]][1]

And it would be so awesome that move based on Swiping position, I mean not automatically goes to that level of position, move with finger tip and when it reach there, just stop moving.

Could anyone help me to implement it, I have no idea how I can do it

Many thanks

1 Answers1

0

Adding completion in UIView.animate in order to turn back to initial state. After a sec or two is depends on your duration in UIView.animate

Code will be like this

UIView.animate(withDuration: 0.5, animations: {
    self.container.transform = CGAffineTransform(rotationAngle: 0.5)
}, completion: {
    _ in
    // turn back to the previous before transform
    self.container.transform = .identity
})

And for your second question, you can implement with touchesBegan and touchesMoved or add PanGesture to handle changing position container view frame like you want.

Thang Phi
  • 1,641
  • 2
  • 7
  • 16
  • Thank you so much for your help. Just could please help me that how I can set a current angle that it moves something like in the image that I set. with 0.5, it rotate from the center of inner square, I need it to rotate from the left or right side of square – martin wotterman Oct 09 '22 at 13:50
  • Dear @martinwotterman, ``CGAffineTransform`` just do the rotation methods of the view. So you can combine with other things to get to what you want. Check this link https://stackoverflow.com/questions/48060394/how-to-rotate-uiview-in-its-top-left-coordinates. – Thang Phi Oct 09 '22 at 13:55