Interface Builderを使わずにUITableViewを使う方法を紹介します。
UIViewControllerを継承した「MyTableViewController」というViewControllerを作ってみます。
▼MyTableViewController.h
UITableViewを利用するための「プロトコル」を指定します
1 2 3 4 5 6 7 8 9 10 11 12 |
#import <UIKit/UIKit.h>
//UITableViewを使うために
//<UITableViewDelegate, UITableViewDataSource>
//という指定を書きます
@interface MyTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
UITableView *tableView;
}
@property (nonatomic, retain) UITableView *tableView;
@end |
▼MyTableViewController.m
delegateとdataSourceの設定、行数/表示データの指定が必須です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
#import "MyTableViewController.h"
@implementation MyTableViewController
@synthesize tableView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { }
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//tableViewを作成
//「delegate」と「dataSource」の指定が必要なのでそれも書いてます。
tableView = [[UITableView alloc] initWithFrame:[self.view bounds]];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
}
//必ず書かなければならないメソッドです。
//tableの行数を指定します。ここでは10にしてあります。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
//必ず書かなければならないメソッドです。
//tableのセルに表示するデータを指定します。
//ここではセルに行番号を表示するように指定してあります。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
cell.text = [NSString stringWithFormat:@"%@ %i", @"row", indexPath.row];
return cell;
}
//tableのセクション数を指定するメソッドです。ここでは1を指定しています。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
//セルが選択された時の動作を指定します。
//ここでは選択された行数をNSLogで出力するように指定しています。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog([NSString stringWithFormat:@"%d selected.", indexPath.row]);
}
//Viewが表示される直前に実行
//セルが選択されていた場合に選択を解除するためのコードをここに書いています
- (void)viewWillAppear:(BOOL)animated
{
NSIndexPath* selection = [myTableView indexPathForSelectedRow];
if(selection){
[myTableView deselectRowAtIndexPath:selection animated:YES];
}
[myTableView reloadData];
}
//Viewが表示された直後に実行
//tableが表示された時にスクロールバーが点滅するように指定しています。
- (void)viewDidAppear:(BOOL)animated
{
[self.myTableView flashScrollIndicators];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)dealloc {
[myTableView release];
[super dealloc];
}
@end |
Related posts: