【问题标题】:How to set default label color based on dark/light mode (in Swift)如何根据暗/亮模式设置默认标签颜色(在 Swift 中)
【发布时间】:2020-05-15 11:35:13
【问题描述】:

我正在尝试将我的 iOS 应用程序更新为暗模式,但在代码中设置暗模式颜色时遇到问题。在编辑 UITextView 时,我希望文本颜色在深色模式下为白色,在浅色模式下为黑色(这是默认标签颜色),但据我所知,我不知道如何在代码中编写它,我该怎么做做吗?

extension AddCardsVC: UITextViewDelegate {
    func textViewDidBeginEditing(_ textView: UITextView) {
        if #available(iOS 13.0, *) {
            definitionInput.textColor = UIColor.(need default label color)
        } else {
            definitionInput.textColor = UIColor.black
        }
        if(definitionInput.text == "organizing items into familiar, manageable units; often occurs automatically"){
            definitionInput.text = ""
        }
    }

}

【问题讨论】:

    标签: ios swift ios-darkmode


    【解决方案1】:
       textView.textColor =  UIColor { tc in
                switch tc.userInterfaceStyle {
                case .dark:
                    return UIColor.white
                default:
                    return UIColor.black
                }
            }
    

    这是最简单的方法,UIColor 可以传递一个带有 traitCollection (TC) 的闭包,并且 traitCollection 有一个名为 userInterfaceStyle 的属性,它告诉用户是否正在使用暗模式,那么你只需执行 switch 语句来选择什么颜色你想回来

    【讨论】:

      【解决方案2】:

      您只需将 UIColor.systemBackground 分配给您的 UITextView 文本颜色

      textView.textColor =  UIColor.systemBackground 
      

      它会在深色模式下自动将文本颜色更改为白色,在浅色模式下自动将文本颜色更改为黑色

      【讨论】:

      • 相反。这将使文本在浅色模式下变白,在深色模式下变暗......
      【解决方案3】:

      你已经调用了这行代码,它在暗模式和亮模式下都可以正常工作。 祝你好运

      label.textColor = .none

      【讨论】:

      • 这对 UILabel 非常有用,正如文档所说:此属性的默认值是系统的标签颜色,它会动态适应暗模式的变化。但是它不适用于 UITextView,文档:默认文本颜色为黑色。
      【解决方案4】:

      或者使用UIColor.label获取系统标签颜色。

      【讨论】:

        猜你喜欢
        • 2019-11-10
        • 2016-01-23
        • 1970-01-01
        • 1970-01-01
        • 2020-11-21
        • 2017-07-28
        • 2021-09-13
        • 1970-01-01
        • 2017-02-04
        相关资源
        最近更新 更多