2014-12-03 41 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; 
} 

现在,每次临时如果方向改变,自定义视图将定位到屏幕的中心。

希望能帮到你。