Search code examples
iphoneanimationcore-animationcatransform3d

CATransform3d a UIButton


I can't seem to get a simple 3d transform to work on a button and the documentation doesn't seem to be helping. I started with a View-based application template. I add in the QuartzCore framework and import it in the ViewController header. In interface builder I drag out two Round Rect Buttons and wire them up to button1, and button2 respectively, and also wire them both to the buttonPressed: method.

A quick run with the animation commented out verifies that only the button that is clicked changes its label.

With the animation back in I get an error Incompatible type for argument 1 of 'setTransform:' on the "sender.transform = t;" line (This is now fixed line changed to [sender.layer setTransform:t];)

How do I get it to rotate 360 degrees. I think the problem is that the start and end states are the same so it doesn't know to rotate through anywhere.

Here is the .h, (i left out the imports for formatting reasons in this post)

@interface animation2ViewController : UIViewController {

    IBOutlet UIButton *button1;
    IBOutlet UIButton *button2;

}

-(IBAction) buttonPressed:(UIButton *)sender;

@end

And the .m file

#import "animation2ViewController.h"

@implementation animation2ViewController

-(IBAction)buttonPressed:(UIButton *)sender {

    [sender setTitle:@"new title" forState:UIControlStateNormal];
    [UIView animateWithDuration:1.0
                          delay:0.0
                        options:UIViewAnimationCurveEaseInOut
                     animations:^{
                         CATransform3D t = CATransform3DIdentity;
                         t.m34 = -1 / 1000;
                         t = CATransform3DRotate(t, 360 * M_PI / 180, 0.0, 1.0, 0.0);  //ultimately want 360 degrees but starting here first
                         [sender.layer setTransform:t];
                     } 
                     completion:^(BOOL finished) {

                     }];

}

Solution

  • M_PI is a rotation of 180°, so that means you do 90 times a 360°.
    try t = CATransform3DRotate(t, M_PI, 0.0, 1.0, 0.0);
    and for the setter error try [sender.layer setTransform:t];
    because you can just transform the layer

    And for the end you need to commit the animation at the end, otherwise it won't animate
    [UIView commitAnimations];