41
43

More than 5 years have passed since last update.

xibで作ったCustomViewをStoryboardで使う

Last updated at Posted at 2015-06-08

(2015/6/30) CustomViewをCustomViewにaddSubviewしてる状態になってたので、こちらの記事を参考に修正しました。

CustomViewの作成

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

@interface CustomView : UIView

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

@interface CustomView () 
//xibのViewをこのプロパティに紐づける
@property (strong, nonatomic) IBOutlet UIView *contentView;

@end

@implementation CustomView

- (void)commonInit {
  NSString* className = NSStringFromClass([self class]);
  [[NSBundle bundleForClass:[self class]] loadNibNamed:className owner:self options:nil];

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

- (instancetype)init {
  self = [super init];

  if (self) {
    [self commonInit];
  }

  return self;
}

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

  if (self) {
    [self commonInit];
  }

  return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
  self = [super initWithFrame:frame];

  if (self) {
    [self commonInit];
  }

  return self;
}

@end

xibの作成

CustomView.xibという名前でxibを作成します。

create_xib.png

xibがloadされてることを確かめやすいように、UILabelを一つ配置しときましょう。

CustomView.xib
xib_label.png

xibのViewを, contentViewに紐づける

CustomView.xibでViewを選び、CustomView.mのcontentViewプロパティに接続しておきます。
20150630162751.png

xibのFile's OwnerをCustomViewに設定する

CustomView.xibでFile's Ownerを選び、IdentityInspectorでCustom ClassをCustomViewにします。
inspector.png

Storyboardへの配置

Main.storyboardで、ViewControllerにUIViewを貼っつけて、Custom ClassにCustomViewを設定します。
四辺にConstraintも設定しときましょう。
(見やすくするため、親viewを灰色にしてます)

main_sb.png

動作確認

Runすると、ちゃんとLabelが貼りついていて、xibがロードされていることがわかります。

iOS Simulator Screen Shot Jun 8, 2015, 9.30.54 PM.png

41
43
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
41
43