List Mac OS 的 SwiftUI 背景色 [英] SwiftUI background color of List Mac OS

查看:16
本文介绍了List Mac OS 的 SwiftUI 背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Mac OS 中使用 ListView.我正在尝试更改该 ListView 的背景颜色.然而,事情并没有想象中那么容易.

I am using a ListView in Mac OS. I am trying to change that background color of that ListView. However, it is not that easy as expected.

我尝试在 ListView 上使用 .background(Color(.red)) 属性.那没有改变任何东西.

I tried using .background(Color(.red)) attribute on the ListView. That didn't change anything.

我只能找到对表格行有影响的 .listRowBackground(Color(.red)).但是,其他背景没有受到影响.

I could only find .listRowBackground(Color(.red))which had an influence on the table rows. However, the other background wasn't effected.

我准备了一个小demo来演示:

I prepared a little demo to demonstrate:

在我看来正文:

  VStack
    {
        List()
        {
            Text("Test")
                .listRowBackground(Color.green)

            Text("Test")
                .listRowBackground(Color.green)

            Text("Test")
                .listRowBackground(Color.green)

        }.background(Color(.red))

    }.background(Color(.red))

这是我得到的结果:

主背景没有变化.我读到了一个改变 UITableView.appearance 的解决方案,但这对我来说在 Mac OS 的 SwiftUI 中是不可能的.

The main background does not change. I read about a solution changing the UITableView.appearance but that is not possible for me in SwiftUI for Mac OS.

提前致谢

推荐答案

更新:我找到了一种更好的方法来删除列表的背景而不影响整个应用程序:使用 自省.

Update: I found a much better way to remove a list's background without affecting the whole app: by using Introspect.

import Introspect
import SwiftUI

extension List {
  /// List on macOS uses an opaque background with no option for
  /// removing/changing it. listRowBackground() doesn't work either.
  /// This workaround works because List is backed by NSTableView.
  func removeBackground() -> some View {
    return introspectTableView { tableView in
      tableView.backgroundColor = .clear
      tableView.enclosingScrollView!.drawsBackground = false
    }
  }
}

用法:

List {
  ForEach(items) { item in
    ...
  }
}.removeBackground()

旧答案:

@Asperi 的回答 有效,但仅在调整窗口大小之前有效.这是覆盖 List 颜色的另一种解决方法:

@Asperi's answer works, but only until the window is resized. Here's another workaround for overriding List's color:

extension NSTableView {
  open override func viewDidMoveToWindow() {
    super.viewDidMoveToWindow()

    backgroundColor = NSColor.clear
    enclosingScrollView!.drawsBackground = false
  }
}

一个潜在的缺点是这会影响应用中的所有列表.

A potential downside is that this will affect all lists in the app.

这篇关于List Mac OS 的 SwiftUI 背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆