lvollmer
lvollmer

Reputation: 1608

set backgroundcolor as UIColor.systembackground in swiftui

Hey i have a Navigation beside my list.

I want that a active navigationitem has the same backgroundcolor as the list.

But i dont see any way to get the color (With compatible Light/Dark mode switch)

I want to set the bluecolor as the systembackground like the right item.

navpic

my code now is like following.

NavigationLink(destination: PersonView()) {
    VStack
    {
        Image("Company").resizable().frame(width:40, height:40).colorMultiply(Color(red: 57 / 255, green: 214 / 255, blue: 155 / 255))
        Text("Companies").foregroundColor(Color(red: 57 / 255, green: 214 / 255, blue: 155 / 255))
    }
}
.buttonStyle(PlainButtonStyle())
.padding(16)
.background(Color(.systemBlue))

Upvotes: -1

Views: 5322

Answers (2)

ingconti
ingconti

Reputation: 11646

my two cents for a fast portable solution between iOS and MacOS (notes from user3441734 do apply, yet) Below a complete small sample from Apple stock template for SwiftUi app. (as a bonus "label", too)

Hope can help others.

enter image description here

import SwiftUI

#if os(iOS)
import UIKit
public typealias EZColor    = UIColor
#elseif os(macOS)
import AppKit
public typealias EZColor    = NSColor
#endif


public extension EZColor {
    #if os(macOS)
    static var label: EZColor {
        return EZColor.labelColor
    }

    static var systemFill: EZColor {
        return NSColor.windowBackgroundColor // works for label, but it's a patch
        //return NSColor.controlColor // works, better for controls, but it's a patch
    }
    #endif
}


public extension Color {
    static var systemFill: Color {
        return Color(EZColor.systemFill)
    }
}



struct ContentView: View {
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            //Text("Hello, world!").background(Color(EZColor.systemFill))
            //Text("Hello, world!").background(Color.systemFill)
            Text("Hello, world!").background(Color.systemFill)
        }
        .padding()
    }
}

Upvotes: 0

user3441734
user3441734

Reputation: 17534

on iOS

Color(UIColor.systemBackground)

on macOS use

Color.init(_ color: NSColor)

NSColor define different background colors for different usage ... for example

NSColor.controlBackgroundColor

or

NSColor.textBackgroundColor

and so on. Check the documentation.

Upvotes: 6

Related Questions