在纵向和横向中使用自动布局

Working with AutoLayout in Portrait and Landscape(在纵向和横向中使用自动布局)

本文介绍了在纵向和横向中使用自动布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Auto Layout 再好不过了,但它让我对约束感到抓狂.我在 IB 中设计了纵向模式,但无法获得所需的横向模式.

Auto Layout, as good as it is, driving me crazy with constraints. I have the portrait mode designed in IB but I can't get the desired landscape orientation to work.

请注意,当方向变为横向时,UIImageView 块之间的间距减小,SAMPLE TEXT 的文本对齐方式变为右对齐.

Notice that when the orientation changes to landscape, the spacing between the UIImageView blocks decreases and the text alignment of SAMPLE TEXT changes to right aligned.

目前,我为它添加了一些约束条件.但是,我需要保持 UIImageView 块之间的空间固定,因此它在纵向看起来很拥挤,而在横向看起来很好.我需要它在纵向上均匀分布并在横向上压缩(如上图所示).同样,目前我的约束会显示文本,但不会将其保持在屏幕中心并右对齐.

Currently, I have added a few constraints for it to work. However, I need to keep the space between UIImageView blocks fixed, as a result of which it looks cramped up in portrait and fine in landscape. I need it to be spread out evenly in portrait and compress in landscape (like in image above). Similarly, currently my constraints bring up the text but it doesnot keep it at the center of screen and right aligned.

自动布局可以实现吗?如果是这样,怎么做?非常感谢您的帮助.

Is this possible at all with Auto Layout? If so, how? Help greatly appreciated.

推荐答案

有几种方法可以解决这个问题.一种方法是将您的 3 个图像视图包含在 UIView 中.将顶部和底部的图像视图约束分别赋予顶部和底部,并赋予中间的一个 centerY 约束.给这个封闭视图一个固定的高度和宽度,以及对控制器视图顶部的约束.为此封闭视图的高度约束创建一个 IBOutlet,并在旋转时更改它.在下面的示例中,我给它的纵向高度为 350:

There are several ways to approach this. One way is to enclose your 3 image views in a UIView. Give the top and bottom image views constraints to the top and bottom respectively, and give the middle one a centerY constraint. Give this enclosing view a fixed height and width, and a constraint to the top of the controller's view. Make an IBOutlet to the height constraint for this enclosing view, and change it on rotation. In the example below, I gave it a height of 350 in portrait:

-(void)updateViewConstraints {
    [super updateViewConstraints];
    if (self.view.bounds.size.height < self.view.bounds.size.width) {
        self.heightCon.constant = self.view.bounds.size.height;
    }else{
        self.heightCon.constant = 350;
    }
}

至于标签,最简单的方法是移除你的约束(bottom 和 centerX),并在旋转时添加 trailing 和 centerY.

As for the label, the easiest way is to remove the constraints you have (bottom and centerX), and add trailing and centerY on rotation.

这篇关于在纵向和横向中使用自动布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在纵向和横向中使用自动布局

基础教程推荐