TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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?

2      

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.

2      

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

2      

I found the solution:

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

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.