2015-11-08 43 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]];