【问题标题】:UILabel changes color back on changing device orientationUILabel 在改变设备方向时改变颜色
【发布时间】:2019-07-02 06:05:55
【问题描述】:

我在情节提要中创建了一个UIViewController。有一个红色的UILabel。经过一些活动后,我将标签上的文本更改为 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
     }
 }

【问题讨论】:

  • 能贴出代码吗?
  • 您的标签是否在UITableViewUICollectionView 内?
  • 标签只是在 ViewController 的视图中。在情节提要中使用自动布局。

标签: ios swift uilabel uicolor


【解决方案1】:

实现 viewDidLayoutSubviews 方法。 ViewDidLayoutSubviews 将被调用

当视图控制器视图的边界发生变化时,视图会调整 子视图的位置,然后系统调用这个方法。

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

【讨论】:

    【解决方案2】:

    您可以在更改标签颜色后调用 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
            }
        }

    【讨论】:

      【解决方案3】:

      如果表格在tableView或collectionView 然后你需要在 cellWillDisplay 中实现你的登录。

      【讨论】:

      • 只是 ViewController 中的标签。没什么特别的
      • 我添加了代码。新控制器在那里打开发生了什么我将一些数据插入到 TextField 中,然后通过委托返回并进入按钮名称并将其颜色和另一种 clLabel 颜色更改为绿色。然后我打开 ipad,颜色变回红色。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      相关资源
      最近更新 更多