Julien
Julien

Reputation: 890

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?

Upvotes: 1

Views: 199

Answers (2)

D. Pass
D. Pass

Reputation: 83

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.

Upvotes: 2

Mohamad Bachir Sidani
Mohamad Bachir Sidani

Reputation: 2099

if(width >= yourDesiredWidth){ 
    yourLabel.textAligment = UITextAligment.center
}
else{
    yourLabel.textAligment = UITextAligment.left
}

Upvotes: 0

Related Questions