简体   繁体   English

中心视图在另一个视图内

[英]Center view inside another view

I have a view called profile which is taking (0,0,320,60) size in storyboard which is taking full width but 60 height, and i am trying to place another view called ranking inside it at the center and what ever the device is iPhone4s,5s,6s,6 it should just take my view and put it at the center. 我有一个称为配置文件的视图,该视图在情节(0,0,320,60)占据了(0,0,320,60)大小,该视图占据了全角但高度为60,并且我试图将另一个名为“排名”的视图放置在中间,以及该设备是什么iPhone4s ,5s,6s,6应该只接受我的看法并将其放在中心。

Here is what i tried: 这是我尝试过的:

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

The current code is not centering my view In all devices. 当前代码未在所有设备中集中显示我的视图。 what can i do to do it dynamically ? 我该怎么做才能动态地做到这一点?

You can use AutoLayout with the following method: 您可以通过以下方法使用自动版式:

+ (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]];
}

You can add the method above in your ViewController or in a helper class. 您可以在ViewController或助手类中添加上述方法。 Remember to set the translatesAutoresizingMaskIntoConstraints property to false before using AutoLayout on your view. 在视图上使用“自动布局”之前,请记住将“ translatesAutoresizingMaskIntoConstraints属性设置为“ false”。

So if ranking is your subview and self.Profile is your superView you can do the following. 因此,如果ranking是您的子视图,而self.Profile是您的超级视图,则可以执行以下操作。

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]];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM