Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

swift - SwiftUI background color of List Mac OS

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.

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

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

I prepared a little demo to demonstrate:

In my view body:

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

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

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

        }.background(Color(.red))

    }.background(Color(.red))

That is the result I get:

enter image description here

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.

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    }
  }
}

Usage:

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

Old answer:

@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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...