如何围绕子视图自身中心旋转?

37

是否可以围绕视图的中心旋转?

在我当前的实现中,子视图(按钮等)似乎会沿着有趣的路径移动,然后才能到达所需的位置(因为超级视图的坐标系被旋转了)。我希望视图像下面图片一样围绕自己的中心旋转90度。

desired rotation


21
+1 为精美插图的问题 - Till
你想让状态栏保持静止,还是这只是插图中被忽视的? - NJones
@NJones 虽然这不是我的主要目标,但如果它保持静止也没关系!在我目前的实现中,子视图沿着“有趣的路径”移动,因为超级视图(或根窗口?)正在旋转。 - ragnarius
2个回答

16

我真的很喜欢这个问题。对于某些界面,我也发现旋转动画很刺眼。这是我如何实现你所描绘的内容。一个简单的@interface就可以了。 注意:我正在使用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

.xib 文件中,需要将适当的输出连接到按钮上:

enter image description here

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

就是这样。现在当你旋转设备时,屏幕不会旋转,但按钮会如所示:

enter image description here

当然,如果你只想让按钮的标签旋转,那么你只需要将变换应用于_buttonA.titleLabel即可。

注意:请注意,一旦设备旋转到触摸不在按钮上的程度,设备仍处于竖屏状态,但您对我的评论的回复似乎表明这对您不是问题。

如果您有相关问题,请随时留言。


非常感谢!代码优雅,子视图现在移动得如此流畅! - ragnarius

4

您可以使用变换属性手动旋转任何UIView子类。

#import <QuartzCore/QuartzCore.h>

myView.transform = CGAffineTransformMakeRotation(M_PI/2);

看起来很简单!但是我必须防止主视图旋转,并找出放置代码片段的位置。 - ragnarius
你应该研究一下UIViewController的旋转回调,比如– shouldAutorotateToInterfaceOrientation:– willRotateToInterfaceOrientation:duration:。看看你能否阻止视图旋转,但仍然订阅旋转事件并相应地更改你的子视图。 - sudo rm -rf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接