Help us understand the problem. What is going on with this article?

xibで作ったCustomViewをStoryboardで使う

More than 3 years have passed since last update.

(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

ocadaruma
Javaを書いています
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした