【问题标题】:iOS: how to change a label alignment based on screen variationiOS:如何根据屏幕变化更改标签对齐方式
【发布时间】:2024-05-02 21:15:02
【问题描述】:

在 IB 中,无法在标签的对齐属性上添加变体。 我的需要是在宽度紧凑时将文本左对齐,当宽度正常时将文本居中。

我该怎么办?

谢谢

【问题讨论】:

    标签: ios alignment label variation


    【解决方案1】:

    您可以将此行为添加到中的网点

    override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
    super.willTransition(to: newCollection, with: coordinator)
    switch newCollection.verticalSizeClass {
            case .compact:
                yourLabel.textAligment = UITextAligment.left
            case .regular, .unspecified:
                yourLabel.textAligment = UITextAligment.center
            }
     }
    

    要确定旋转,您使用verticalSizeClass,要确定设备类型(例如iPad 或iPhone),您使用horizo​​ntalSizeClass。

    【讨论】:

    • 不幸的是,与通过代码创建 UI 元素相比,IB 创建和操作 UI 元素的可能性要小一些。
    【解决方案2】:
    if(width >= yourDesiredWidth){ 
        yourLabel.textAligment = UITextAligment.center
    }
    else{
        yourLabel.textAligment = UITextAligment.left
    }
    

    【讨论】:

      最近更新 更多