4

根据在 iOS 上实现暗模式,我们需要将 foregroundColor 属性设置为新的标签颜色。这是如何使用界面生成器完成的?

我尝试使用“文本颜色”选项并将颜色设置为 Developer->labelColor,但这不起作用。

编辑:由于目前这是不可能的,我使用了这个解决方法:

override func viewDidLoad() {
    // Support Dark Mode
    if #available(iOS 13.0, *) {
        let attributes = NSMutableAttributedString(attributedString: textView.attributedText!)
        attributes.addAttribute(.foregroundColor, value: UIColor.label, range: NSRange(location: 0, length: attributes.mutableString.length))
        textView.attributedText = attributes
    }
}
4

4 回答 4

7

您不能在 Interface Builder 中执行此操作。您必须.foregroundColor在代码中设置属性。

let mas = NSMutableAttributedString(string:s, attributes:[
    .font:UIFont(name:"GillSans", size:15)!,
    .foregroundColor:UIColor.label,
]
于 2019-09-22T18:21:25.793 回答
3

不确定属性,但我可以将属性文本的颜色设置为最容易支持的暗模式之一:

textView.textColor = UIColor.label
于 2020-02-05T19:05:40.067 回答
1
static let textColor = UIColor { traitCollection in
    if traitCollection.userInterfaceStyle == .dark {
        return .white
    } else {
        return .black
    }
}

let attributedText: [NSAttributedString.Key: Any] = [
        .font: font,
        .foregroundColor: UIColor.textColor
    ]
于 2020-11-12T11:23:52.543 回答
1

我找到了一个简单的解决方法:如果将 UILabel 更改为“纯”文本,则可以指定暗模式支持的颜色,例如“标签颜色”,然后可以将文本更改为“属性”。现在它正在使用 Attributed Text 属性,但它仍然使用您之前指定的颜色。如果您不手动更改颜色,它将保持此颜色。您仍然可以更改字体大小和粗细。

编辑:我注意到有时当您在 IB 中更改字体大小时,Xcode 会为您更改颜色......完全破坏了暗模式的自动颜色更改。您可以丢弃这些更改: 故事板差异

于 2020-12-24T07:24:57.507 回答