LoginSignup
10
11

More than 5 years have passed since last update.

カスタムxibを手軽にコードから使用する

Posted at

APIからの値を繰り返し表示したり、フォームを動的に生成したい場合とかに割と便利なカスタムviewの作り方のメモ

  • UIViewを継承したクラスとXibを同じ名前で作成する。(同じにすることで、xib読み込み時にファイル名を指定する必要がなくなります。)
  • 作成したxibのCustom Classに作成したクラスを指定する。
  • 以下のコードをクラスに実装

作成したクラスに追加したコード

SampleView.h
+ (instancetype)view;
SampleView.m
+ (instancetype)view
{
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
    id view = [nib instantiateWithOwner:self options:nil][0];
    return view;
} 

使用方法

SampleViewクラスとSampleView.xibを作成した場合の呼び出し方です。

sample.m
- (void)viewDidLoad
{
    SampleView *sampleView = [SampleView view];
    [self.view addSubview:sampleView];
}

はまったところ

autolayoutを使用している時は、frameをいくら変更してもviewが変更されないため,

view.translatesAutoresizingMaskIntoConstraints = YES;

のように、autolayoutを解除する必要があります。
autolayoutの設定があることに気がつかずに、数時間無駄にしたのでメモです。

参考とか

10
11
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
10
11