Stany Miles
Stany Miles

Reputation: 212

UILabel changes color back on changing device orientation

I created a UIViewController in storyboard. There is a UILabel colored red. After some activity I change text on the label and it's textColor to green.

The strange thing is: when I change device orientation label's textColor changes back to red as it was at the beginning, but text stays.

How can I do that textColor on the label stays green after device rotation?

class ViewController: UIViewController {

     @IBOutlet private weak var volumeButton: UIButton!
     @IBOutlet private weak var clLabel: UILabel!

     override var traitCollection: UITraitCollection {
         if view.bounds.width < view.bounds.height {
             let traits = [UITraitCollection(horizontalSizeClass: .compact), UITraitCollection(verticalSizeClass: .regular)]
             return UITraitCollection(traitsFrom: traits)
         } else {
             let traits = [UITraitCollection(horizontalSizeClass: .regular), UITraitCollection(verticalSizeClass: .compact)]
             return UITraitCollection(traitsFrom: traits)
         }
     }

     @IBAction private func handleInputVolume(_ sender: UIButton) {
         coordinator?.inputData(type: .volume, delegate: self)
     }
}

 extension ViewController: InputDataReceivable {

     func didFinishInput(volume: Double) {
         volumeButton.setTitle(volume.formattedString, for: .normal)
         volumeButton.setTitleColor(.enabledGreen, for: .normal)
         clLabel.textColor = .enabledGreen
     }
 }

Upvotes: 0

Views: 416

Answers (3)

Hitesh Borse
Hitesh Borse

Reputation: 479

Implement viewDidLayoutSubviews method. ViewDidLayoutSubviews will be called

When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls this method.

override func viewDidLayoutSubviews() {
    label.textColor = UIColor.green
}

Upvotes: 2

Nahid Raihan
Nahid Raihan

Reputation: 1017

You can check it after calling the self.view.layoutIfNeeded() after change your label color. If its not work then use following code just change the label color programmatically again when your orientation change.

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        if(size.width > self.view.frame.size.width){
            //Landscape
            yourLabel.textColor = UIColor.green
        }
        else{
            //Portrait
           yourLabel.textColor = UIColor.green
        }
    }

Upvotes: 1

Abhishek Maurya
Abhishek Maurya

Reputation: 765

If the table is in tableView or collectionView Then you'll need to implement your login in cellWillDisplay.

Upvotes: 0

Related Questions