Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 14:14
Show Gist options
  • Save memfrag/5477ba586c6ec38b6350 to your computer and use it in GitHub Desktop.
Save memfrag/5477ba586c6ec38b6350 to your computer and use it in GitHub Desktop.
Interface Builder Designable Custom View
#import <UIKit/UIKit.h>
// IB_DESIGNABLE means that the view will be
// rendered live in Interface Builder.
@interface MJPlaceholderView : UIView
// IBInspectable means that the property
// will be editable in the Attributes
// inspector panel in Interface Builder.
@property (nonatomic, copy) IBInspectable NSString *text;
@property (nonatomic, assign) IBInspectable CGFloat textSize;
@property (nonatomic, strong) IBInspectable UIColor *textColor;
@property (nonatomic, strong) IBInspectable UIColor *fillColor;
@property (nonatomic, assign) IBInspectable CGFloat cornerRadius;
#import "MJPlaceholderView.h"
@implementation MJPlaceholderView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self != nil) {
// This is run when the view is created
// in Interface Builder.
return self;
- (void)prepareForInterfaceBuilder {
[super prepareForInterfaceBuilder];
* If you need to create code for a custom view that runs
* only in Interface Builder, call that code from the method
* prepareForInterfaceBuilder. For example, while designing
* an app that uses the iPhone camera, you might want to draw
* an image that represents what the camera might capture.
* Although it’s compiled for runtime, code called from
* prepareForInterfaceBuilder never gets called except by
* Interface Builder at design time.
- (CGFloat)cornerRadius {
return self.layer.cornerRadius;
- (void)setCornerRadius:(CGFloat)cornerRadius {
self.layer.cornerRadius = cornerRadius;
self.layer.masksToBounds = cornerRadius > 0.0f;
- (void)drawRect:(CGRect)rect {
// This is only compiled for the interface builder.
// This is only compiled for runtime.
[(_fillColor ?: [UIColor magentaColor]) set];
NSString *size = [NSString stringWithFormat:@"%u x %u",
[self drawCenteredText:size verticalOffsetInMultipleOfHeight:0.5f];
[self drawCenteredText:(self.text ?: @"Placeholder") verticalOffsetInMultipleOfHeight:-0.5f];
- (void)drawCenteredText:(NSString *)text verticalOffsetInMultipleOfHeight:(CGFloat)offsetMultiple {
CGFloat fontSize = _textSize > 1.0f ? _textSize : 16.0f;
NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Light" size:fontSize],
NSForegroundColorAttributeName:_textColor ?: [UIColor blackColor]};
CGSize size = [text sizeWithAttributes:attributes];
CGRect rect = self.bounds;
CGRect r = CGRectMake(rect.origin.x + (rect.size.width - size.width) / 2.0,
rect.origin.y + (rect.size.height - size.height) / 2.0 + size.height * offsetMultiple,
[text drawInRect:r withAttributes:attributes];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment