Skip to content

Instantly share code, notes, and snippets.

@NikKovIos
Last active April 30, 2020 20:40
Show Gist options
  • Save NikKovIos/d86fa4c7ae6c2d644f8c762f1d5f76b0 to your computer and use it in GitHub Desktop.
Save NikKovIos/d86fa4c7ae6c2d644f8c762f1d5f76b0 to your computer and use it in GitHub Desktop.
Objective-C Class for loading view from xib
//
// NibInstantiableView.h
// nik-kov.com
//
// Created by Nik Kov on 23.03.2018.
// Copyright © 2018 Apple. All rights reserved.
//
#import <UIKit/UIKit.h>
/// Just subclass it and assign the contentView property in xib to the root view of the xib. File owner must be your class type.
IB_DESIGNABLE
@interface NibInstantiableView : UIView
@end
//
// NibInstantiableView.m
// nik-kov.com
//
// Created by Nik Kov on 23.03.2018.
// Copyright © 2018 Apple. All rights reserved.
//
#import "NibInstantiableView.h"
@interface NibInstantiableView()
@property (weak, nonatomic) UIView *contentView;
@end
@implementation NibInstantiableView
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super initWithCoder:coder];
if (self) [self setup];
return self;
}
- (instancetype)init
{
self = [super init];
if (self) [self setup];
return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) [self setup];
return self;
}
- (void)setup
{
self.backgroundColor = [UIColor clearColor];
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class])
bundle:bundle];
UIView *view = [nib instantiateWithOwner:self options:nil][0];
self.contentView = view;
self.contentView.frame = self.bounds;
[self.contentView setAutoresizingMask: UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight];
self.contentView.translatesAutoresizingMaskIntoConstraints = YES;
[self addSubview:self.contentView];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment