Xcode: Dark mode doesn't work if the color is in the framework
Asked Answered
B

2

6

On xcode I work within a workspace where there is a basic project and a framework. All colors are defined within the framework. When I configure a label with the color assets of the framework from the basic project on storyboard, the color is taken correctly, but if I then switch to dark mode, the color does not change, it always remains the same.

Configuration color label in project

setting textColorBlack in dark mode should appear white but it doesn't work.

textColorBlack in framework project

I don't understand what the problem is.

Belcher answered 8/3, 2021 at 10:13 Comment(2)
Please remove any. only dark and light select. please try itIntercrop
I tried to remove it, but it still doesn't workBelcher
O
4

Xib/Storyboard just preserves selected color name (visible at dev time from all spaces), but in run-time on color schema changes it cannot find it, because by default it searches by name in main bundle.

Instead we have to assign color programmatically specifying exact location of color, like

override func viewDidLoad() {
    super.viewDidLoad()

    label.textColor = UIColor(named: "myColor", 
          in: Bundle(identifier: "framework_identifier") ?? .main,  // << here !!
          compatibleWith: .current)
}

@IBOutlet weak var label: UILabel!

Tested with Xcode 13.4 / iOS 15.5

demo

Octave answered 9/8, 2022 at 8:39 Comment(1)
I'd go so far and call it bug in storyboard code. Named colors in swift packages work otherwise. The light/dark version works, when viewed in Interface Builder and then you start the app and pull your hair out. :-( Thanks anyway for the explanation.Kazue
B
3

In our case we defined some extensions, that load the corresponding Colors from the asset catalog:

public extension Color {
    public enum Primary {
        static let green = Color("PrimaryGreen", bundle: .module)
    }
}
public extension UIColor {
    public enum Primary {
        static let green = UIColor(Color.Primary.green)
    }
}

SwiftUI's Color is loaded directly from the asset catalog, but UIKit's UIColor is instantiated from the loaded Color. This causes the described problem, since the UIColor won't automatically update, when switching to dark mode. The solution, of course, is to also load the UIColor directly from the asset catalog .

Brutish answered 9/8, 2022 at 10:34 Comment(1)
Thanks, this worked for us, so the bounty is yours. I do not know if it also works for the original poster.Proctology

© 2022 - 2024 — McMap. All rights reserved.