Search code examples
xcodecocoainterface-builderibdesignableibinspectable

IB_DESIGNABLE Class not rendering on Interface Builder


This is my first try with IB_DESIGNABLE on Xcode.

I have this class to add color to a NSView.

header

#import <Cocoa/Cocoa.h>


IB_DESIGNABLE @interface NSViewComCor : NSView

@property (nonatomic, weak) IBInspectable NSColor *backgroundColor;

@end

implementation

#import "NSViewComCor.h"

@implementation NSViewComCor

@synthesize backgroundColor = _backgroundColor;

- (void)awakeFromNib {

  [super awakeFromNib];

  [self setWantsLayer:YES];
  self.backgroundColor = [NSColor whiteColor];  //default color
}

- (NSColor *) backgroundColor
{
  CGColorRef colorRef = self.layer.backgroundColor;
  return [NSColor colorWithCGColor:colorRef];
}

- (void) setBackgroundColor:(NSColor *)backgroundColor
{ // color should change when changed on interface builder inspectable color box
  self.layer.backgroundColor = backgroundColor.CGColor;
  _backgroundColor = backgroundColor;
}

even with IB_DESIGNABLE, this class does not render with the correct color on interface builder... why?


Solution

  • As the point out in WWDC 2014 "What's New in Interface Builder" video, you have to:

    1. Create framework.

    2. Create class.

    3. Mark view as designable (and properties as inspectable).

    4. Go back to the main project and specify the base class in Interface Builder.

    For example, I added a new "framework" target to the project, and added the following NSView subclass source to that framework:

    IB_DESIGNABLE @interface CustomView : NSView
    
    @property (nonatomic, strong) IBInspectable NSColor *backgroundColor;
    
    @end
    

    and

    @implementation CustomView
    
    - (void)drawRect:(NSRect)dirtyRect {
        [super drawRect:dirtyRect];
    
        [self.backgroundColor setFill];
        NSRectFill(dirtyRect);
    }
    
    @end
    

    Then, when I went back to my main project and tried adding this CustomView as a subview on my storyboard, the "background color" was IB "inspectable" and I could see the changes in the color immediately rendered in IB.