BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Different background style for dark mode and light mode

Forums > SwiftUI

 ScrollView(.horizontal) {

                let color: HierarchicalShapeStyleModifier<BackgroundStyle>? = (colorScheme == .dark ? BackgroundStyle.background.tertiary as? HierarchicalShapeStyleModifier<BackgroundStyle> : BackgroundStyle.background.secondary as? HierarchicalShapeStyleModifier<BackgroundStyle>)

                LazyHStack {
                    content
                        .padding(12)
                        .frame(width: 300, alignment: .center)
                        .frame(maxHeight: .infinity, alignment: .center)
                        .background(color!, in: .rect(cornerRadius: 20))
                }
                .scrollTargetLayout()
            }

I have this code where I'm trying to use different .background style for dark mode and light mode. In the .background I have to force unwrap the value. How can I do it better?

   

Wouldn't it give you the same result?

let color = colorScheme == .dark ? Color(uiColor: .tertiarySystemBackground) : Color(uiColor: .secondarySystemBackground)

As far as I understand it is the same color. But maybe I am wrong.

   

You might be better to go to Assets.xcasssets file and add a new Color Set Have one color for Any Appearance and one for Dark then you can do

.background(Color("YourBackgroundColorName"), in: .rect(cornerRadius: 20))

or in iOS 17

.background(Color.YourBackgroundColorName, in: .rect(cornerRadius: 20))

And let the system take care of the colors

   

I found the solution:

           let color: AnyShapeStyle = colorScheme == .dark ? AnyShapeStyle(.tertiary) : AnyShapeStyle(.secondary)

   

Hacking with Swift is sponsored by Guardsquare

SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.