khuong291 khuong291 - 7 months ago 70
Swift Question

Rotate image -45 degree

I am building example about FloatingButton.

But I have some troubles with rotate image. I want it to rotate like this link

https://github.com/yoavlt/LiquidFloatingActionButton

But my button is:

enter image description here

As you can see, when I click the first time, it run well :D, it transform like

x
, but when I click again, I want it back to original like
+
, but it doesn't work well.

Here is my code:

import UIKit

class ViewController: UIViewController {

@IBOutlet var floatingButton: UIImageView!
var floatingButtonIsActive = false

override func viewDidLoad() {
super.viewDidLoad()

addShadowToFloatingButton()
let gesture = UITapGestureRecognizer(target: self, action: #selector(floatingButtonTapped(_:)))
floatingButton.addGestureRecognizer(gesture)
}

private func addShadowToFloatingButton() {
floatingButton.layer.shadowColor = UIColor.grayColor().CGColor
floatingButton.layer.shadowOffset = CGSize(width: -2, height: 2)
floatingButton.layer.shadowOpacity = 1
floatingButton.layer.shadowRadius = 1
}

func floatingButtonTapped(sender: UITapGestureRecognizer) {

if floatingButtonIsActive == false {

UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: .CurveEaseInOut, animations: {
self.floatingButton.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
}, completion: { _ in
self.floatingButtonIsActive = true
})

} else {
UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: .CurveEaseInOut, animations: {
self.floatingButton.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_4))
}, completion: { _ in
self.floatingButtonIsActive = false
})
}
}
}


Any helps would be appreciated. Thanks.

Answer

Set the transform to CGAffineTransformIdentity when you are done. That is the transform that it originally had. When you set the transform, you are telling it the absolute angle to rotate to, regardless of what angle it is currently at.

func floatingButtonTapped(sender: UITapGestureRecognizer) {

    if floatingButtonIsActive == false {

        UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: .CurveEaseInOut, animations: {
            self.floatingButton.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
            }, completion: { _ in
                self.floatingButtonIsActive = true
        })

    } else {
        UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: .CurveEaseInOut, animations: {
            self.floatingButton.transform = CGAffineTransformIdentity
            }, completion: { _ in
                self.floatingButtonIsActive = false
        })
    }
}
Comments