この記事はLiT!関西 Advent Calendar 2014 17日目の記事です。 LiT(Life is Tech!)とは中学生、高校生のためのプログラミング・ITキャンプ/スクールのことであり、このアドベントカレンダーは、LiT所属の大学生メンターが書いています。
xibファイル...?
ファイルを追加します
iOS/User InterfaceからViewを選びます、CustomViewと名づけましょう。
Viewは固定Sizeになっているかと思うので、SizeをFreedomにし、
ここでは、100x100にしておきます。
ここが重要、先ほど名付けた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を押したら簡単に生成できます。
上手く使って再利用していきたい
*補足:CustomTableViewCell.xibも登録してCellを再利用しています。
- (void)viewDidLoad {
    [super viewDidLoad];
    UINib *nib = [UINib nibWithNibName:@"CustomTableViewCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"Cell"];
}




