在swiftui中设置backgroundcolor为UIColor.systembackground

46scxncf  于 2023-05-16  发布在  Swift
关注(0)|答案(2)|浏览(97)

我有一个导航在我的列表旁边。
我想一个积极的navigationitem有相同的backgroundcolor作为名单。
但是我看不出有什么方法可以得到颜色(有兼容的亮/暗模式开关)
我想像正确的项目一样设置蓝色作为系统背景。

我现在的代码如下。

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

y3bcpkx11#

我的两分钱用于iOS和MacOS之间的快速便携式解决方案(来自user3441734的注解确实适用,然而)下面是来自Apple股票模板的SwiftUi应用程序的完整小样本。(也作为奖金“标签”)
希望可以帮助别人。

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()
    }
}
3duebb1j

3duebb1j2#

在iOS上

Color(UIColor.systemBackground)

在macOS上使用

Color.init(_ color: NSColor)

NSColor为不同的用途定义不同的背景颜色...例如

NSColor.controlBackgroundColor

NSColor.textBackgroundColor

等等。查看文档。

相关问题