How to rotate sub-views around their own centres?

♀尐吖头ヾ 提交于 2019-11-29 21:20:15

I really like this question. I also find the rotation animation jarring for some interfaces. Here's how I would implement what you have pictured. A simple @interface will be just fine. Note: I am using ARC.

#import <UIKit/UIKit.h>
@interface ControllerWithRotatingButtons : UIViewController
@property (strong, nonatomic) IBOutlet UIButton *buttonA;
@property (strong, nonatomic) IBOutlet UIButton *buttonB;
@property (strong, nonatomic) IBOutlet UIButton *buttonC;
@end

The appropriate outlet connections are made to the buttons in the .xib:

ControllerWithRotatingButtons.m:

#import "ControllerWithRotatingButtons.h"
@implementation ControllerWithRotatingButtons
@synthesize buttonA = _buttonA;
@synthesize buttonB = _buttonB;
@synthesize buttonC = _buttonC;
-(void)deviceRotated:(NSNotification *)note{
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    CGFloat rotationAngle = 0;
    if (orientation == UIDeviceOrientationPortraitUpsideDown) rotationAngle = M_PI;
    else if (orientation == UIDeviceOrientationLandscapeLeft) rotationAngle = M_PI_2;
    else if (orientation == UIDeviceOrientationLandscapeRight) rotationAngle = -M_PI_2;
    [UIView animateWithDuration:0.5 animations:^{
        _buttonA.transform = CGAffineTransformMakeRotation(rotationAngle);
        _buttonB.transform = CGAffineTransformMakeRotation(rotationAngle);
        _buttonC.transform = CGAffineTransformMakeRotation(rotationAngle);
    } completion:nil];
}
-(void)viewDidLoad{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceRotated:) name:UIDeviceOrientationDidChangeNotification object:nil];
}
-(void)viewDidUnload{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end

And that's it. Now when you rotate your device the screen will not rotate but the buttons will as shown:

Of course if you only want the button's labels to turn you would simply apply the transform to the _buttonA.titleLabel instead.

Note: Please note that once the device is rotated as far as any touches not on the buttons are concerned the device is still in portrait, but your response to my comment seems to indicate that's not a problem for you.

Feel free to leave a comment if you have a related question.

You can manualy rotate any UIView subclass using transform property.

#import <QuartzCore/QuartzCore.h>

myView.transform = CGAffineTransformMakeRotation(M_PI/2);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!