github twitter email
Remove Background Effect From NSCollectionView
Jun 16, 2022
One minute read

If you set windowBackgroundColor as the backgroundColor of your NSCollectionView the background color is modified dynamically by the system to incorporate color from the underlying desktop image.

However, applying the same color to a NSViewController’s view does not have the same effect.

The screenshot below shows the visual effect of this configuration in dark mode.

Visual Studio Code Snippet

If you really want your NSCollectionView to have the same background color as your ViewController’s view, you have to use the following line of code:

collectionView.backgroundColors = [.clear]

For completenes, below is a minimal example that illustrates the effect.


import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // set the view's background color
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.windowBackgroundColor.cgColor
        
        // create the collection view inside a scroll view
        let collectionView = NSCollectionView()
        let scrollView = NSScrollView()
        scrollView.frame = NSRect(x: 0, y: 0, width: 300, height: 300)
        scrollView.documentView = collectionView
        view.addSubview(scrollView)
        
        // set a layout, otherwise nothing is rendered
        let flowLayout = NSCollectionViewFlowLayout()
        collectionView.collectionViewLayout = flowLayout
        
        // set the same color as the collection view's background color
        collectionView.backgroundColors = [.windowBackgroundColor]
    }

}

Credit goes to Umur Gedik.


Tags: macOS

Back to posts