LoginSignup
76
73

More than 5 years have passed since last update.

カスタム UIView を xib から作る方法

Last updated at Posted at 2012-12-26

Interface Builder での実装例

View テンプレートから xib ファイルを新規作成したら、ビューの Custom Class を指定します。File's Owner の方は不要です。
1.png


ビュー上にコントロール類を配置して制御する場合はカスタムビュークラスの IBOutlet/IBAction に接続します。
2.png

コードの実装例

ポイントは UINib です。サブクラスを作って UINib を使ってビューのインスタンスを得ます。
※ xib ≒ nib です。

MyView.h

@interface MyView : UIView

+ (instancetype)myView;

@end

MyView.m

@interface MyView ()

@property (weak, nonatomic) IBOutlet UISwitch *switch;

- (IBAction)buttonAction:(id)sender;

@end

@implementation MyView

- (void)_init
{
    // initialize
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self _init];
    }
    return self;
}
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self _init];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];

    // 初期設定など
}

+ (instancetype)myView
{
    // xib ファイルから MyView のインスタンスを得る
    UINib *nib = [UINib nibWithNibName:@"MyView" bundle:nil];
    MyView *view = [nib instantiateWithOwner:self options:nil][0];
    return view;
}

- (IBAction)buttonAction:(id)sender
{
    // アクションを実装
}

@end

使い方


MyView *customView = [MyView myView];
[view addSubView:customView];

76
73
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
76
73