【问题标题】:How to rotate sub-views around their own centres?如何围绕自己的中心旋转子视图?
【发布时间】:2012-02-05 07:48:43
【问题描述】:

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

在我目前的实现中,子视图(按钮等)似乎在它们最终到达所需位置之前沿着一条有趣的路径移动(因为超级视图的坐标系已旋转)。我希望视图围绕它们自己的中心旋转 90 度,如下图所示。

【问题讨论】:

  • +1 说明问题很好
  • 您希望状态栏保持静止,还是只是在插图中被忽略了?
  • @NJones 虽然这不是我的主要目标,但如果它保持静止就可以了!在我目前的实现中,子视图沿着“有趣的路径”移动,因为超级视图(或根窗口?)正在旋转。

标签: ios rotation autorotate


【解决方案1】:

我真的很喜欢这个问题。我还发现某些界面的旋转动画不和谐。以下是我将如何实现您所描绘的内容。一个简单的@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中的按钮进行了适当的插座连接:

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

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

当然,如果您只希望按钮的标签转动,您只需将转换应用于 _buttonA.titleLabel

注意:请注意,一旦设备旋转至按钮以外的任何触摸,设备仍处于纵向状态,但您对我的评论的回复似乎表明这不是你的问题。

如果您有相关问题,请随时发表评论。

【讨论】:

  • 非常感谢!代码很优雅,子视图现在移动得非常流畅!
【解决方案2】:

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

#import <QuartzCore/QuartzCore.h>

myView.transform = CGAffineTransformMakeRotation(M_PI/2);

【讨论】:

  • 看起来很简单!但不知何故,我必须阻止主视图旋转,并找出代码 sn-p 的放置位置。
  • 您应该查看UIViewController 旋转回调,例如– shouldAutorotateToInterfaceOrientation:– willRotateToInterfaceOrientation:duration:。看看你是否可以保持视图不旋转,但仍然订阅旋转事件并相应地更改你的子视图。
猜你喜欢
  • 2014-03-05
  • 2019-10-22
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2017-05-04
  • 1970-01-01
相关资源
最近更新 更多