I have implemented a collection view on my Cocoa app following Ray Wenderlich's tutorial (very helpful, given how buggy and broken Apple's API is in this area).
In the tutorial, the collection view's canvas is colored black using the following code (all code is in view controller class' viewDidLoad()
method):
collectionView.layer?.backgroundColor = NSColor.black.cgColor
However, the area that "peeks" when you overshoot ("rubber-band") the scroll using -for example- a magic mouse/scrollwheel, is still white and very distracting:
I'm trying to make the whole content area black. In my storyboard, I set the background color of both the NSScrollView
and NSClipView
that contain the collection view to black, but it doesn't change the appearance.
Also tried the programmatic alternative: setup an outlet for the scrollview and call:
self.scrollview.backgroundColor = NSColor.black
self.scrollview.contentView.backgroundColor = NSColor.black
...to no effect.
Additionally, I tried:
collectionView.superview?.layer?.backgroundColor = NSColor.black.cgColor
...but this doesn't work either.
Neither does:
self.view.layer?.backgroundColor = NSColor.black.cgColor
or:
self.view.window?.backgroundColor = NSColor.black
Update:
I have set the background color of the scroll view to red, and drawsBackground
to true
(both in IB and programmatically). The docs for NSScrollView
's backgroundColor
property say:
This color is used to paint areas inside the content view that aren’t covered by the document view.
I have verified at runtime that the document view is indeed my collection view:
if scrollview.documentView is NSCollectionView {
print("Document is collection")
}
However, no red is displayed and the area beyond the document (collection view) stays white.
Update 2: I fired the View Hierarchy Debugger, and it seems that the value of drawsBackground
is false at runtime (I set it to true
in both code and storyboard)!:
(the background color itself seems to be reflected, though)
- In Interface Builder, select the CollectionView in the document outline.
- In the Utilities window, show the Attributes inspector.
- Set the desired color in the Primary color selector control.
Note: the Ray Wenderlich tutorial that you referenced sets the background color of the collection view programmatically. You'll either want to remove that line, or ensure that you are setting the same color that you chose in step 3 above.
for changing it programmatically in Swift 3 use e.g.:
collectionView.backgroundColors = [NSColor.black]
Just change self.view.wantsLayer = true
in self.collectionView.wantsLayer = true
来源:https://stackoverflow.com/questions/42778317/how-to-color-the-overshoot-background-of-an-nscollectionview