Transparent NSCollectionView Background
Asked Answered
E

3

11

I'm again struggling with setting NSViews background colors to transparent. I have a NSCollectionView as part of NSClipView which is part of a NSScrollview. My MainViewController has an outlet to the collectionView. With adding the two lines of code and after compiling the background is sometimes transparent but most of the times not:

view.wantsLayer = true
collectionView.layer?.backgroundColor = NSColor.clear.cgColor

I also tried to select/de-select the "Draw Background" property of the NSScrollView in the IB without any effects. What do I miss here.

Expiate answered 5/2, 2017 at 23:3 Comment(2)
Cocoa is not so kind as UIKit. Yet, it'd just be the matter of creating a subclass.Dread
El Tomato, thanks for the response. What do I need to subclass and why? Thanks.Expiate
F
10

I struggled a bit attempting to get my NSCollectionView background "transparent" @JFS solution pointed me in the right direction: and I finally achieved it by setting both the parent scrollView and the collectionView backgrounds:

cvScrollView.backgroundColor = NSColor.clear
collectionView.backgroundColors = [NSColor.clear]
Fracas answered 7/5, 2018 at 14:49 Comment(0)
E
8

Ok, after a long evil trial and error phase I found a solution at least for myself. There are two background colors to set in order to have the proper behavior:

  1. the background color of the NSScrollView:

enter image description here

  1. the NSCollectionView primary color:

enter image description here

Both have to be set appropriately. At the point I set both to the same color I got the background I want. With setting only the ScrollView background color there was still the white background when scrolling the items in the CollectionView.

Expiate answered 6/2, 2017 at 19:8 Comment(0)
A
5

To make clear background for NSScrollView, the best option in Swift 4.2 is "Not draw a background". Let's get to view a programmatically example:

let scrollView = NSScrollView()
scrollView.drawsBackground = false
scrollView.contentView.drawsBackground = false

NSCollectionView has background for sections, so you need to specify colors for sections

let collectionView = NSCollectionView()
collectionView.backgroundColors = [.clear]

If you set backgroundColors to nil or to empty array, the background color is set by default to white.

If you set a background view for NSCollectionView, this array is ignored

You could try to put a NSView with frame zero as a backgroundView for NSCollectionView

Archivist answered 9/2, 2019 at 21:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.