在IB中使用Autolayout如何以编程方式将UIView放置在屏幕中央?

我有一个UIView,我想要在主视图上水平居中,然后在主视图上垂直居中,减去大约14个像素。

如果我用IB设置它,它可以在Retina 3.5上运行,但是在Retina 4上运行的时候,它的亮度大约是40像素。

我认为最好的解决scheme是基于屏幕高度以编程方式build立这些约束?

使用centerX和centerY常数,并将常量设置为14(或-14不知道您希望的方式),

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:0 toItem:view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]]; [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterY relatedBy:0 toItem:view attribute:NSLayoutAttributeCenterY multiplier:1 constant:14]]; 

为了使您的视图在中心(水平和垂直)。 在界面生成器中select视图,然后从顶部菜单中select编辑器>alignment>容器中的容器/垂直中心中的水平中心。

您还可以添加更多的约束来满足视图的几何。