gpt4 book ai didi

列表Mac OS的SwiftUI背景颜色

转载 作者:行者123 更新时间:2023-12-03 09:20:04 25 4
gpt4 key购买 nike

我在Mac OS中使用ListView。我试图更改该ListView的背景颜色。但是,这并不像预期的那么容易。

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

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

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

在我看来:

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

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

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

}.background(Color(.red))

}.background(Color(.red))

那就是我得到的结果:

enter image description here

主要背景没有改变。我读到有关更改 UITableView.appearance的解决方案的信息,但是在Mac OS的SwiftUI中,这对我来说是不可能的。

提前致谢

最佳答案

更新:通过使用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's answer有效,但仅在调整窗口大小之前有效。这是覆盖 List颜色的另一种解决方法:
extension NSTableView {
open override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()

backgroundColor = NSColor.clear
enclosingScrollView!.drawsBackground = false
}
}
潜在的缺点是,这将影响应用程序中的所有列表。

关于列表Mac OS的SwiftUI背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60454752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com