LoginSignup
10
9

More than 5 years have passed since last update.

iOSメモ - xibファイルで作成したCustomViewを生成しよう

Last updated at Posted at 2014-12-17

この記事はLiT!関西 Advent Calendar 2014 17日目の記事です。 LiT(Life is Tech!)とは中学生、高校生のためのプログラミング・ITキャンプ/スクールのことであり、このアドベントカレンダーは、LiT所属の大学生メンターが書いています。

xibファイル...?

xibと.nibの違い

ファイルを追加します

スクリーンショット 2014-12-18 0.15.15.png

iOS/User InterfaceからViewを選びます、CustomViewと名づけましょう。

スクリーンショット 2014-12-18 0.13.37.png

Viewは固定Sizeになっているかと思うので、SizeをFreedomにし、

スクリーンショット 2014-12-17 23.55.17.png

ここでは、100x100にしておきます。

スクリーンショット 2014-12-17 23.55.35.png

ここが重要、先ほど名付けたCustomView、typoしないように...
UIView *subview = [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil][0];

せっかくなのでbackgroundColor変えましょう

#import "ViewController.h"

@interface ViewController (){
    int count;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (IBAction)addCustomView{
    count++;
    UIView *subview = [[NSBundle mainBundle] loadNibNamed:@"CustomView" owner:self options:nil][0];
    subview.frame = CGRectMake(100, count * 100, 100, 100);

    [self setRandomColor:subview];
    [self.view addSubview:subview];
}

- (void)setRandomColor:(UIView *)subview {
    CGFloat hue = ( arc4random() % 256 / 256.0 );  //  0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  //  0.5 to 1.0, away from black
    UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
    subview.backgroundColor = color;
}

@end

関連付けを忘れずに、Buttonを押したら簡単に生成できます。

スクリーンショット 2014-12-18 0.08.53.png

上手く使って再利用していきたい

*補足:CustomTableViewCell.xibも登録してCellを再利用しています。

- (void)viewDidLoad {
    [super viewDidLoad];
    UINib *nib = [UINib nibWithNibName:@"CustomTableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"Cell"];
}
10
9
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
9