Home > Software design >  SwiftUI - Making a button suitable for light and dark mode
SwiftUI - Making a button suitable for light and dark mode

Time:03-22

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)?

CodePudding user response:

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

CodePudding user response:

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

  • Related