I want to rotate my UIButton
by M_PI/4
with animation. Here's my code:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[UIView animateWithDuration:.5 animations:^{
self.closeButton.transform = CGAffineTransformMakeRotation(M_PI/4);
}];
}
But this make my button's frame corrupted. Frame before animation was (260 0; 44 44)
and after animation it becomes (250.887 -9.1127; 62.2254 62.2254)
.
I saw this post and few others, but I don't understand, how to achieve UIButton animated rotation by M_PI/2
.
You may rotate UIImageView itself with: UIImageView *iv = [[UIImageView alloc] initWithImage:image]; iv. transform = CGAffineTransformMakeRotation(M_PI_2); Or if you really want to change image, you may use code from this answer, it works.
The frame
property is invalid once you've applied a transformation. According to the documentation:
Warning: If the transform property is not the identity transform, the value of this property is undefined and therefore should be ignored.
So as long as the result looks alright this is expected behavior.
If you want to move the button, you need to save the transformation, reset it to CGAffineTransformIdentity
, set the new frame, then re-apply the old transformation. Alternatively, you may access and modify the center
property of the frame even when a transformation is applied.
The frame
of a UIView is the smallest rectangle that fully encloses the view. When you rotate by PI/2 the frame will expand by sqrt(2), and the origin will be adjusted to keep the center at the same point, which is exactly what happened.
If you want the button to rotate and keep its same frame, you need to squash the button as it rotates, like this
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
CGFloat w = self.closeButton.bounds.size.width / sqrtf( 2.0f );
CGFloat h = self.closeButton.bounds.size.height / sqrtf( 2.0f );
NSLog( @"%@ w=%f", NSStringFromCGRect( self.closeButton.bounds ), w );
[UIView animateWithDuration:.5 animations:^{
self.closeButton.transform = CGAffineTransformMakeRotation(M_PI/4);
self.closeButton.bounds = CGRectMake( 0, 0, w, h );
}];
NSLog( @"%@", NSStringFromCGRect( self.closeButton.frame ) );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With