Skip to content

Instantly share code, notes, and snippets.

@izackp
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izackp/1e1e08958fd95eba7412 to your computer and use it in GitHub Desktop.
Save izackp/1e1e08958fd95eba7412 to your computer and use it in GitHub Desktop.
Widget class which allows you to inherit from widget and create a xib file with the same name as the class. Once this is done you can reuse the xib anywhere by setting a view's subclass.
#import <UIKit/UIKit.h>
@interface Widget : UIView
@property (strong, nonatomic, readonly) IBOutlet UIView* view;
@end
#import "Widget.h"
@interface Widget ()
@property (strong, nonatomic, readwrite) UIView* view;
@end
@implementation Widget
- (void)awakeFromNib {
[super awakeFromNib];
[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil];
[self fitUIIfNecessary];
[self addSubview:self.view];
}
- (void)fitUIIfNecessary {
[self fitWidthWithContentIfNecessary];
[self fitHeightWithContentIfNecessary];
}
- (void)fitWidthWithContentIfNecessary {
bool flexableWidth = (self.view.autoresizingMask & UIViewAutoresizingFlexibleWidth);
if (!flexableWidth)
self.width = self.view.width;
}
- (void)fitHeightWithContentIfNecessary {
bool flexableHeight = (self.view.autoresizingMask & UIViewAutoresizingFlexibleHeight);
if (!flexableHeight)
self.height = self.view.height;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment