UIView を nib/xib で定義して使う場合の雛形

  • 43
    Stock
  • 0
    Comment
Stock this post
  • crexista
  • Kendroid
  • sotarof@github
  • PGMY
  • mzyy94
  • numa08
  • kita
  • ofl
  • toshinarin
  • bells17
  • ...

実装側

MyView.h
@interface MyView : UIView

+ (id)myView;

@end
MyView.m
@interface MyView ()

@property (weak, nonatomic) IBOutlet UIButton *button;

- (IBAction)buttonAction:(id)sender;

@end

#pragma mark -

@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];

    // コントロールの値を設定
}

// MRC
- (void)dealloc
{
    [_button release];

    [super dealloc];
}
// ---

+ (id)myView
{
    // nib ファイルから読み込む
    UINib *nib = [UINib nibWithNibName:@"MyView" bundle:nil];
    MyView *view = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
    return view;
}

@end

呼び出し側

Hoge.m
- (void)method
{
    MyView *view = [MyView myView];
}

xib の定義

  • View のクラスを "MyView" に設定
  • サブビューを View の Outlet / Action に接続
  • File's Owner の設定は不要
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account log in.