2014-12-03 77 views
0

我創建了一個自定義的UIView,並將其放置到一個視圖控制器,我希望把它放在所有設備的中心(的iPad,iPhone)佈局的UIView

所以我做這個

CGRect screenRect = [[UIScreen mainScreen] bounds];

self.center = CGPointMake((screenRect.size.height/2),(screenRect.size.width/2));

但它僅與iPad/lanscape工作

我如何佈局這一觀點在中心屏幕關閉所有設備,所有方向

+0

使用AutoLayout。 – Fogmeister 2014-12-03 10:48:12

+0

使用自動佈局。 – Andy 2014-12-03 14:20:12

回答

1

它不是好的做法,當時的觀點是自我定位,你應該從你的視圖控制器,例如在viewWillAppear中,檢查做到這一點,是你viewControllers觀點是全屏,並做到這一點:

CGRect rect = [self.view bounds]; 

self.yoursView.center = CGPointMake((rect.size.width/2),(rect.height./2)); 
+0

「寬度」應該作爲第一個參數來正確居中: 'CGPointMake((rect.size.width/2),(rect.size.height/2))' – Michael 2014-12-03 08:35:44

+0

是的,我沒有注意到。 – mityaika07 2014-12-03 08:46:18

+0

或者你也可以使用'CGPointMake(CGRectGetMidX(rect),CGRectGetMidY(rect))' – Lefteris 2014-12-03 09:19:35

0

不知道如果我的回答是,你在找什麼,但我看到它的方式,你必須將視圖控制器視圖的中心設置爲自定義視圖的中心。這應該發生在每個方向。

具體而言,我們假設您有一個名爲的自定義視圖testView

最初創建時你寫:

self.testView.center = self.view.center; 

,在這兩個的iOS 8和以前的版本的作品是觀察的UIDeviceOrientationDidChangeNotification通知,當設備的方向得到改變通知的實用方法。然後,您可以再次設置自定義視圖的中心,如上所示。

例如,在viewDidLoad方法讓你的類遵守了上述通知:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOrientationChangeWithNotification:) name:UIDeviceOrientationDidChangeNotification object:nil]; 

接下來,聲明無論是私下或公開的handleOrientationChangeWithNotification:方法:

@interface ViewController() 

-(void)handleOrientationChangeWithNotification:(NSNotification *)notification; 

@end 

最後,實現它如下:

-(void)handleOrientationChangeWithNotification:(NSNotification *)notification{ 
    self.testView.center = self.view.center; 
} 

現在,每次臨時如果方向改變,自定義視圖將定位到屏幕的中心。

希望能幫到你。