2012-01-08 59 views
36

是否可以圍繞自己的中心旋轉視圖?如何在他們自己的中心周圍旋轉子視圖?

在我現在的實現中,子視圖(按鈕等)似乎沿着一個有趣的路徑移動,直到它們到達期望的位置(因爲超級視圖的座標系被旋轉)。如下圖所示,我希望觀點能夠圍繞自己的中心旋轉90度。

desired rotation

+21

對於很好地說明問題的+1 – Till 2012-01-08 11:59:15

+0

你想讓狀態欄保持靜止,還是僅僅是在插圖中被忽視? – NJones 2012-01-09 02:56:32

+0

@NJones雖然這不是我的主要目標,但如果它仍然保持不變,那就沒問題!在我目前的實現中,子視圖沿着一個「有趣的路徑」移動,因爲超級視圖(或根窗口?)在旋轉。 – ragnarius 2012-01-09 18:56:41

回答

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代替。

注:請注意,一旦該設備只要不上的按鈕任何觸摸而言旋轉的設備仍處於肖像,但你對我的評論的反應似乎表明,這不是你的問題。

如果您有相關問題請隨時留下評論。

+0

非常感謝!該代碼是優雅的,子視圖現在移動如此光滑! – ragnarius 2012-01-10 18:51:34

+0

幹得好!非常高效! – Nil 2017-07-09 08:05:22

4

您可以manualy使用旋轉變換財產的任何UIView子類。

#import <QuartzCore/QuartzCore.h> 

myView.transform = CGAffineTransformMakeRotation(M_PI/2); 
+0

看起來很簡單!但不知何故,我必須阻止主視圖旋轉,並找出將代碼片段放在哪裏。 – ragnarius 2012-01-08 19:35:07

+0

您應該查看'UIViewController'循環回調,例如' - shouldAutorotateToInterfaceOrientation:'和willRotateToInterfaceOrientation:duration:'。看看你是否可以保持旋轉視圖,但仍然訂閱旋轉事件並相應地更改您的子視圖。 – 2012-01-08 20:47:06