6
6

More than 5 years have passed since last update.

UIView単位でXIBを読み込むための汎用クラス

Posted at

説明

Objective-C / SwiftでUIViewをUIパーツとして使いまわしたい場合、
UIViewごとにXIBファイルを定義しておくと便利です。
ロード処理を汎用化したクラスを作って使っているので紹介します。

このクラスは以下の条件で動作します:

  • このクラスのサブビューとしてビューを定義した場合、initWithFrame:あるいはinitWithCoder: が呼ばれると、自分のクラス名と同じ名前のxibファイルをロードします
  • ロードしたxibのルートビューは、ロードしたビュー自身の直下にサブビューとして追加されます
  • ロードされるXIBのownerは、ロードするビューのクラスが設定されていること
  • ロードされるXIBのルートビューは、YMUIXIBViewのIBOutlet, baseにリンクされていること

Snippet

YMUIXIBView.h
#import <UIKit/UIKit.h>

// ************************************************************
#pragma mark - Class
// ************************************************************
@interface YMUIXIBView : UIView

@property(nonatomic, strong) IBOutlet UIView *base;

- (instancetype)initWithFrame:(CGRect)frame;
- (instancetype)initWithCoder:(NSCoder *)aDecoder;

@end
YMUIXIBView.m
#import "YMUIXIBView.h"

// ************************************************************
#pragma mark - Private interface
// ************************************************************
@interface YMUIXIBView(){

}
- (void)loadXIB;

@end


// ************************************************************
#pragma mark - Implementation
// ************************************************************
@implementation YMUIXIBView

// ------------------------------------------------------------
#pragma mark - Initializers
// ------------------------------------------------------------
- (instancetype)initWithFrame:(CGRect)frame{
    if(!(self = [super initWithFrame:frame]))
        return nil;

    [self loadXIB];
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if(!(self = [super initWithCoder:aDecoder]))
        return nil;

    [self loadXIB];
    return self;
}

// ------------------------------------------------------------
#pragma mark - Private methods
// ------------------------------------------------------------
- (void)loadXIB{
    self.base = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class)
                                               owner:self
                                             options:nil] firstObject];
    self.base.autoresizingMask
        = UIViewAutoresizingFlexibleWidth
        | UIViewAutoresizingFlexibleHeight;


    [self addSubview:self.base];
    self.base.frame = self.bounds;
}

@end
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6