首页 文章

自动布局方向更改为纵向但不是水平

提问于
浏览
0

我以横向方向设计了我的应用程序的布局,但当它以纵向方式显示时,我希望将所有 UILabels 向下移动10个左右的像素 . 我尝试通过使用自动布局设置上限制来执行此操作 . 我能够以纵向获得我想要的位置,但它也改变了横向方向的 UILabels 的位置 . 我想将所有标签转为 IBOutlets 并以编程方式更改其位置 . 但我想知道是否有更简单或更有效的解决方案?

1 回答

  • 0

    您可以向UILabel添加约束,并在更改方向时更改它们 . 例如,向UILabel添加一个约束,使其从屏幕顶部开始x像素 . 移动到纵向时,可以将约束更新为x 10 .

    @interface YourClass()
    
    @property (nonatomic, strong) UILabel *label;
    @property (nonatomic, strong) NSLayoutConstraint *constraint;
    
    @end
    
    @implementation YourClass
    
    - (void)setupConstraints {
        self.constraint = [NSLayoutConstraint constraintWithItem:self.label
                                                       attribute:NSLayoutAttributeTop
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:self.view
                                                       attribute:NSLayoutAttributeHeight
                                                      multiplier:0
                                                        constant:20];
    }
    
    // Call this method every time orientation changes.
    - (void)updateConstraints {
        if([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait) {
            self.constraint.constant = 30;
        } else {
            self.constraint.constant = 20;
        }
    }
    
    @end
    

相关问题