UILabel 在改变设备方向时改变颜色

UILabel changes color back on changing device orientation

我在故事板中创建了一个 UIViewController。有一个 UILabel 红色。在一些 activity 之后,我将标签上的文本更改为 textColor 为绿色。

奇怪的是:当我更改设备方向标签时,textColor 变回了开始时的红色,但文本保持不变。

如何才能让设备旋转后标签上的 textColor 保持绿色?

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

如果 table 在 tableView 或 collectionView 中 然后您需要在 cellWillDisplay 中实现您的登录。

您可以在更改标签颜色后调用 self.view.layoutIfNeeded() 进行检查。如果它不起作用,则使用以下代码,只需在方向更改时再次以编程方式更改标签颜色即可。

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

实现 viewDidLayoutSubviews 方法。 ViewDidLayoutSubviews 将被调用

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
}