开发者

How to rotate a UIbutton in Xcode + IB?

开发者 https://www.devze.com 2022-12-23 16:15 出处:网络
I am writing an iPhone programer, and I want to make a button with is rotate 180 degree, I try to use the multi-touch track pad to r开发者_C百科otate a UIbutton, but it don\'t success, how can I do i

I am writing an iPhone programer, and I want to make a button with is rotate 180 degree, I try to use the multi-touch track pad to r开发者_C百科otate a UIbutton, but it don't success, how can I do it? or I need to do it by code?


You can't do it from Interface Builder. You have to rotate it from your code, using the transform property of your UIButton, which is a CGAffineTransform struct. You can use the CGAffineTransformMakeRotation() to set it.

myButton.transform = CGAffineTransformMakeRotation( ( 180 * M_PI ) / 180 );

The first 180 in the code is the angle in degrees. The operation converts it to radians.


I was wanting to do this same thing - rotate a button 180 degrees when tapped - but do it using an animation. Neurofluxation's answer does the 180 degree rotation with an animation, but it isn't permanent. Macmade's answer does the 180 degree rotation, but doesn't do it with an animation. So if you're like me and would like to do a 180 degree rotation with animation use this code:

[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.35];

// (180 * M_PI) / 180 == M_PI, so just use M_PI
myButton.transform = CGAffineTransformMakeRotation(M_PI);

[UIView commitAnimations];

As well, if you want to rotate back to the starting position (ie 0 degree rotation) then put the following in between the animation code like above:

myButton.transform = CGAffineTransformMakeRotation(0);

As to a use case for such a button, Evernote's show/hide keyboard button does a really slick 180 degree rotation which can be recreated using the above code.


Well, here we go:

CABasicAnimation *halfTurn;
halfTurn = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
halfTurn.fromValue = [NSNumber numberWithFloat:0];
halfTurn.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
halfTurn.duration = 0.5;
halfTurn.repeatCount = 1;
[myButton addAnimation:halfTurn forKey:@"180"];

Hope that helps... Im typing from my PC though, not my Mac - So I hope that's right!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号