Skip to content

Instantly share code, notes, and snippets.

@jblebrun
Created October 17, 2014 17:10
Show Gist options
  • Save jblebrun/3633993a38a470c74c67 to your computer and use it in GitHub Desktop.
Save jblebrun/3633993a38a470c74c67 to your computer and use it in GitHub Desktop.
Shadows and corner radius in interface builder!
#import <UIKit/UIKit.h>
@interface UIView (Inspectable)
@property (nonatomic) IBInspectable CGFloat cornerRadius;
@property (nonatomic) IBInspectable BOOL circular;
@property (nonatomic) IBInspectable CGFloat shadowRadius;
@property (nonatomic) IBInspectable CGFloat shadowOpacity;
@property (nonatomic) IBInspectable CGSize shadowOffset;
@property (nonatomic) IBInspectable UIColor* shadowColor;
@end
#import "UIView+Inspectable.h"
#import "objc/runtime.h"
@interface Circularifier : NSObject
@property (nonatomic) BOOL circular;
@property (nonatomic, weak) UIView* view;
@property (nonatomic) CGFloat oldRadius;
@end
@implementation Circularifier
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ( _circular ) {
_oldRadius = _view.layer.cornerRadius;
_view.layer.cornerRadius = MIN(_view.frame.size.height, _view.frame.size.width) / 2;
} else {
_view.layer.cornerRadius = _oldRadius;
}
}
@end
@implementation UIView (Inspectable)
-(CGFloat)cornerRadius
{
return self.layer.cornerRadius;
}
-(void)setCornerRadius:(CGFloat)cornerRadius
{
Circularifier* c = objc_getAssociatedObject(self, @selector(circular));
c.oldRadius = cornerRadius;
self.layer.cornerRadius = cornerRadius;
}
-(BOOL)circular {
return self.layer.cornerRadius == MIN(self.frame.size.height, self.frame.size.width) / 2;
}
-(void)setCircular:(BOOL)circular
{
Circularifier* c = objc_getAssociatedObject(self, @selector(circular));
if (!c) {
c = [[Circularifier alloc] init];
objc_setAssociatedObject(self, @selector(circular), c, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
c.view = self;
}
if ( circular ) {
[self.layer addObserver:c forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
[self.layer addObserver:c forKeyPath:@"bounds" options:NSKeyValueObservingOptionNew context:nil];
} else {
[self.layer removeObserver:c forKeyPath:@"frame"];
[self.layer removeObserver:c forKeyPath:@"bounds"];
}
c.circular = circular;
}
-(void)setShadowColor:(UIColor*)shadowColor
{
self.layer.shadowColor = shadowColor.CGColor;
}
-(UIColor*)shadowColor
{
return [UIColor colorWithCGColor:self.layer.shadowColor];
}
-(void)setShadowOffset:(CGSize)shadowOffset
{
self.layer.shadowOffset = shadowOffset;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment