2015-11-08 59 views
0

我有一个观点叫做轮廓,其正在(0,0,320,60)尺寸故事板这是在充分宽度,但60的高度,我试图把所谓的在中心里面排名另外的看法,什么都装置是iPhone4s,5s,6s,6它应该把我的看法放在中心位置。中心观点

这里是我的尝试:

ranking.frame = CGRectMake(0, 0, 120, 60); 
ranking.center = self.Profile.center; 

目前的代码是不居中我认为在所有的设备。我能做些什么来动态地做到这一点?

+1

使用约束和自动布局,不** **通过代码创建UI。首先让它开始工作将是一件痛苦的事情。维护它将会更加有效。 – luk2302

+1

@ luk2302:那是什么***):d:P –

+0

轮廓图是共享的视图,其被放置在10个控制器,所以我不想在10个故事板创建它。 –

回答

2

您可以使用自动版式以下方法:

+ (void)centerView:(UIView *)view inContainerView:(UIView *)containerView withSuperView:(UIView *)superView 
{ 
    [superView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0.0]]; 
    [superView addConstraint:[NSLayoutConstraint constraintWithItem:view attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:containerView attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0.0]]; 
} 

你可以在你的ViewController或在辅助类添加方法同上。 请记住在您的视图上使用AutoLayout之前,将translatesAutoresizingMaskIntoConstraints属性设置为false。

所以,如果ranking是你的子视图和self.Profile是你的SuperView,你可以做到以下几点。

UIView *ranking = [[UIView alloc] init]; 
ranking.translatesAutoresizingMaskIntoConstraints = false; 
[self.Profile addSubview:ranking]; 
[[self class] centerView:ranking inContainerView:self.Profile withSuperView:self.Profile]; 
[self.Profile addConstraint:[NSLayoutConstraint constraintWithItem:ranking attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:120]]; 
[self.Profile addConstraint:[NSLayoutConstraint constraintWithItem:ranking attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:60]];