您需要自己對視圖應用轉換。您應該將此變換viewDidLayoutSubviews
,以確保當視圖佈局正確應用的變換,並且還註冊UIDeviceOrientationDidChangeNotification
通知並重新應用設備方向的變化變換時。
-(void)_applyTransform
{
CGAffineTransform t = CGAffineTransformIdentity;
if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft)
{
t = CGAffineTransformMakeRotation(M_PI/2.0);
}
else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)
{
t = CGAffineTransformMakeRotation(-M_PI/2.0);
}
else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown)
{
t = CGAffineTransformMakeRotation(M_PI);
}
[_view setTransform:t];
}
- (void)_deviceOrientationDidChange:(NSNotification*)n
{
[self _applyTransform];
}
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
[self _applyTransform];
}
添加人的答案的粉絲! :)只是爲了記錄,這裏有一整套使用Leo真棒示例的典型工作代碼。
假設你有一個UIView類,所以,通常匹配你正在加載的XIB。在這個例子中,視圖有四個按鈕。 iPhone旋轉時我們會旋轉按鈕。 (要清楚的是,我們只是在旋轉,我們想要的是 - 在這個例子中,我們並沒有旋轉整個視圖,你可以旋轉東西,移動項目,隱藏東西或任何你想要的東西,或者你可以可以旋轉整個視圖,如果相關的話。處理更廣泛的調整大小的問題是不同的,這個例子顯示「只」旋轉該死的按鈕。)
(順便說一句,通常我會建議使用可能的類別在這裏,但這是一個很好的例子來展示它是如何工作的,那麼直接貼入代碼。)
注意,它圍繞動畫按鈕旋轉。
@implementation SomeUIView
-(id)initWithCoder:(NSCoder*)coder
{
self = [super initWithCoder:coder];
if (!self) return nil;
// your other setup code
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(spun)
name:UIDeviceOrientationDidChangeNotification object:nil];
NSLog(@"added ok...");
return self;
}
-(void)dealloc
{
NSLog(@"removed ok...");
// your other dealloc code
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:UIDeviceOrientationDidChangeNotification object:nil];
}
,然後旋轉按鈕(或任何你想要的)......
-(void)spinOneThing:(UIView *)vv
{
CGAffineTransform t = CGAffineTransformIdentity;
if ([[UIDevice currentDevice] orientation] ==
UIDeviceOrientationLandscapeLeft)
t = CGAffineTransformMakeRotation(M_PI/2.0);
if ([[UIDevice currentDevice] orientation] ==
UIDeviceOrientationLandscapeRight)
t = CGAffineTransformMakeRotation(-M_PI/2.0);
if ([[UIDevice currentDevice] orientation] ==
UIDeviceOrientationPortraitUpsideDown)
t = CGAffineTransformMakeRotation(M_PI);
[UIView animateWithDuration:0.1 animations:^{ [vv setTransform:t]; }];
}
-(void)spun // the device was spun by the user
{
NSLog(@"spun...");
[self spinOneThing:self.buttonA];
[self spinOneThing:self.buttonB];
[self spinOneThing:self.buttonC];
[self spinOneThing:self.buttonD];
}
你試試我的解決方案? –