Change background color in NSCollectionView

Can I programmatically change the background color of an NSCollectionView?

I tried to subclass .. but does not work.

@interface CollectionViewBg : NSCollectionView 

in .m

  [self setBackgroundColors:[NSArray arrayWithObjects:[NSColor blueColor], nil]]; 
+6
source share
3 answers

In .m, delete this line:

  [self setBackgroundColors:[NSArray arrayWithObjects:[NSColor blueColor], nil]]; 

And use this code:

 - (void)drawRect:(NSRect)dirtyRect{ [[NSColor blueColor] setFill]; NSRectFill(dirtyRect); } 

Also remember to change the class of the NSCollectionView object in IB to CollectionViewBg.

Hope this helps :)

+3
source

Guess that subclassing is not a great idea, because most Cocoa controls provide different methods to avoid subclassing in order to customize the look and behavior.

In this particular case, you can set the backgroundView property to your NSCollectionView and provide a custom view designed to paint a custom background.

If you need to change only the background color, then you might consider using the fact that viewing a collection usually resists inside scrolling. Just set the backgroundColor and drawsBackground properties of the NSScrollView .

0
source

Here is a more modern solution. First, create a subclass of NSView that draws on the effect you want to achieve. Here is a simple one that draws the color of the block:

 class ColouredView: NSView { @IBInspectable var color: NSColor = .windowBackgroundColor override func draw(_ dirtyRect: NSRect) { color.setFill() dirtyRect.fill() } } 

Now go to the pen or storyboard and drag the custom view to the left pane. We do not want it to be part of the view hierarchy, but we want it to appear under the view controller that contains the collection view. Just drag it below "First Responder". Then you can set any important properties or relationships - in my case, the background color.

Finally, right-click your collector view and connect its "background view" output to your custom view. This allows you to make all the settings in your storyboard. If you like, you can make your own look @IBDesignable but I find this usually causes more problems than it's worth it.

0
source

Source: https://habr.com/ru/post/901362/


All Articles