Search code examples
ioslabelalignment

iOS: how to change a label alignment based on screen variation


In IB, there's no way to add a variation on the alignment property of a label. My need is to align the text on left when width is compact and centered when width is regular.

How can I do it?


Solution

  • You can add this behavior to the outlets in

    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
            }
     }
    

    For determining rotating you use verticalSizeClass, for determining device type (such iPad or iPhone) you use horizontalSizeClass.