Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Making a button suitable for light and dark mode

Tags:

button

swiftui

HStack(spacing: 15) {
        ForEach(0..<button.count, id: \.self) {button in
                Button(action: {
                    self.buttonContinue = button
                    
                }) {
                    Text("\(self.button[button])").padding(.vertical, 12.5)
                        .padding(.horizontal, 120)
                        .foregroundColor(.white)
                        .background(self.buttonContinue == button ? Color.black: Color.gray)
                    .clipShape(Capsule())}}

        }

I have used this code to create a continue button. In light mode, the colours work well (from a grey background and white text to a black background and white text), however, when I switch to dark mode the background of the button disappears from grey to nothing when clicked. Is there anyway I can change the background of the button to white with dark mode (as when I have tried I can only change the text colour)?

like image 491
user3907 Avatar asked Oct 15 '25 19:10

user3907


2 Answers

In you case you could simply do:

                Text("Button \(button)")
                    .padding(.vertical, 12.5)
                    .padding(.horizontal, 120)
                    .foregroundStyle(.background)
                    .background(2 == button ? Color.primary: Color.secondary)
                    .clipShape(Capsule())

or for more control use:

@Environment(\.colorScheme) var colorScheme

var textColor: Color {
    if colorScheme == .dark {
        return Color.white
    } else {
        return Color.black
    }
}

or follow @loremipsum and define your own colors in Assets

like image 94
ChrisR Avatar answered Oct 18 '25 04:10

ChrisR


You can use either a UIColor in the Color(uiColor:) init, or create your own color asset which has an Any Appearance(light) and dark mode color. Using UIColor is below:

Text("\(self.button[button])").padding(.vertical, 12.5)
    .padding(.horizontal, 120)
    .foregroundColor(.white)
    // See below for the appropriate inits:              
    .background(self.buttonContinue == button ? Color(uiColor: .labelColor): Color(uiColor: .systemGrayColor)
    .clipShape(Capsule())}}

Or using a Color Asset:

enter image description here

like image 37
Yrb Avatar answered Oct 18 '25 03:10

Yrb