Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create background for NSView when using storyboards with OS X

I know how I may be able to do this programmatically. I know that when creating storyboards for iOS it's very easy and is right there in the attributes inspector. However when creating storyboards for OS X, I don't see it for any of my view controllers or the view underneath it in Xcode 6.1.1

How can I change the background of the view without having to create a view controller associated with it. My application has a lot of views that are simple, but the background changes colour from one view to the next.

like image 343
Alex Avatar asked Feb 06 '15 16:02

Alex


3 Answers

Here is another way to achieve the same effect.

Add NSBox under your NSView and adjust NSBox's frame as the same with the NSView.

Change Title position to None, Box type to Custom, Border Type to None

This is the screenshot:

enter image description here

And than add your NSView, NSButton, NSTextField or whatever as a subview of NSBox.

This is the result:

enter image description here

like image 176
JZAU Avatar answered Oct 12 '22 02:10

JZAU


You shouldn't need a new viewController to change the background of an NSView. If you aren't subclassing NSView, then you can simply call:

myView.wantsLayer = true
myView.layer!.backgroundColor = CGColorGetConstantColor(kCGColorBlack)

I'm not sure if you can do it strictly in the storyboard, though you can likely set the wantsLayer = true in storyboard using the User Defined Runtime Attributes.

enter image description here

like image 31
Jeremy Pope Avatar answered Oct 12 '22 01:10

Jeremy Pope


You can change a NSView's background color in the storyboard if you subclass NSView and assign the subclass to your view:

enter image description here

enter image description here

Using this subclass implementation:

import Cocoa

class ViewWithBackgroundColor : NSView {
    @IBInspectable var backgroundColor: NSColor? {
        get {
            guard let layer = layer, backgroundColor = layer.backgroundColor else { return nil }
            return NSColor(CGColor: backgroundColor)
        }

        set {
            wantsLayer = true
            layer?.backgroundColor = newValue?.CGColor
        }
    }

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
}

The background color isn't shown at design time but at run-time.

Maybe somebody got an idea how to also update the view at design time (preferably without overriding the draw method).

like image 24
Lars Blumberg Avatar answered Oct 12 '22 03:10

Lars Blumberg