xcodeswift-playgroundxcode11ios-darkmode

How to simulate dark mode on iOS Xcode Swift Playground


Similar to How to use dark mode in simulator iOS 13? and How to enable Dark Mode on the Simulator?, how can you enable dark mode in the Xcode Swift Playground Live View?


Solution

  • You can test it in any view using overrideUserInterfaceStyle

    As an example, you can paste this code in a playground to check it (tested in Xcode 11.3.1):

    import Foundation
    import PlaygroundSupport
    
    extension UIColor {
    
        static var primary: UIColor {
            UIColor { trait -> UIColor in
                return trait.userInterfaceStyle == .light ? .black : .white
            }
        }
    
        static var secondary: UIColor {
            UIColor { trait -> UIColor in
                return trait.userInterfaceStyle == .light ? .white : .black
            }
        }
    }
    
    class DarkModeTestView: UIView {
    
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 375, height: 300))
    
        override init(frame: CGRect) {
            super.init(frame: frame)
    
            backgroundColor = .secondary
    
            label.text = "This text should be displayed in black for light mode and white for dark mode"
            label.textColor = .primary
            label.numberOfLines = 0
    
            addSubview(label)
        }
    
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
    let testView = DarkModeTestView(frame: CGRect(x: 0, y: 0, width: 375, height: 300))
    testView.overrideUserInterfaceStyle = .dark // Change here .light or .dark
    
    PlaygroundPage.current.liveView = testView