UITableViewの使い方手順
はじめに
TableViewControllerを使わず、ViewControllerにTableViewをおいて作る手順です
実装
1. TableViewをおく(StoryBoard、プログラム)
StoryBoard上のViewの上にTableViewをドラッグアンドドロップして追加
Main.storyboardのTableViewをViewController.hに右クリックしながらドラッグアンドドロップして名前をつける。ここではtableViewとする
2. TableViewCellを作成
新規ファイル作成で、UITableViewCellクラスのサブクラスを作成。XIBファイルも同時に作成
ここではTableViewCellという名前にする。また、identifierも必ずつける。ここでは「TableViewCell」とする
3. TableViewCellにアイテムを追加(StoryBoard、プログラム)
TableViewCell.xibにLabelをドラッグアンドドロップして追加
TableViewCell.xibのLabelをTableViewCell.hに右クリックしながらドラッグアンドドロップして名前をつける。ここではlabelTitleとする
4. TableViewに表示するデータを準備(プログラム)
ViewController.m
@interface ViewController ()
@property(nonatomic, strong) NSMutableArray *tableData;
@end
- (void) viewDidLoad {
self.tableData = [NSMutableArray array];
for (int i=0; i<100; i++) {
NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:
@"テスト", @"title",
nil];
[self.tableData addObject:data];
}
}
5. ViewControllerにTableViewの設定を追加(プログラム)
ViewController.h
@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
ViewController.m
- (void) viewDidLoad {
self.tableView.delegate = self;
self.tableView.dataSource = self;
UINib *nib = [UINib nibWithNibName:@"TableViewCell" bundle:nil];
[self.tableView registerNib:nib forCellReuseIdentifier:@"TableViewCell"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return self.tableData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"TableViewCell";
ThirdViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.labelTitle.text = self.tableData[indexPath.row][@"title"];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 129;//ここはTableViewCell.xibに設定されてる行の高さをかえす
}以上です