Ilias Karim
Ilias Karim

Reputation: 5371

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?

Upvotes: 5

Views: 1290

Answers (3)

Iulian Onofrei
Iulian Onofrei

Reputation: 9730

Use .environment(\.colorScheme, .light) and .environment(\.colorScheme, .dark):

import PlaygroundSupport
import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Test")
    }
}

PlaygroundPage.current.setLiveView(
    VStack {
        ContentView()
            .environment(\.colorScheme, .light)
        ContentView()
            .environment(\.colorScheme, .dark)
    }
        .frame(width: 500, height: 500)
        .padding()
        .background(Color.accentColor)
)

screenshot

Upvotes: 0

PabloLerma
PabloLerma

Reputation: 680

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

Upvotes: 3

Furkan Armakan
Furkan Armakan

Reputation: 9

the simulator is very likely to an actual device. For this solution, run your simulator in Xcode. After the simulator home screen shows up, go to the settings menu on your simulator, on the settings menu there is a developer menu. Click on the developer menu and you will see the dark appearance switch. If you switch that bar then all your apps will be run in dark mode. (If your app has a dark mode version).

How to open dark mode appearance with Xcode in Simulator Device

Upvotes: 0

Related Questions