UITableViewでリスト表示するっす | ゆぅさんのiPhone開発技術関連ブログ

ゆぅさんのiPhone開発技術関連ブログ

iPhone開発についての技術まわりのことを切り出して書き込みします。

UITzbleViewでリスト表示をしてみるときのめもめも合格

UITableViewは項目を一覧でリスト表示して、選択するときに使うビュー。
テーブルっていっても、HTMLのテーブルみたいにタテヨコにセルができるわけではないみたい。

UITableViewの処理は、
表示するデータの内容本体をUITableViewDataSourceプロトコルで、
選択したときの処理をUITableViewDelegateプロトコルで
定義する。

最低限、これだけ設定してあればOKなはず。。。

【UITableViewDataSource】
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
リストの項目数を返す

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
リストの1項目分のセルのオブジェクトを返す


【UITableViewDelegate】
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
ぽちっと押されたときに呼ばれるので、押された時の処理を書く



サンプルのMyTableViewのソース

@interface MyTableView: UITableView{

}
@end

@implementation MyTableView


- (id)init{
self = [super init];
self.frame = CGRectMake(0, 0, 320, 460);
self.delegate = self;
self.dataSource = self;
return self;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 15;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
int index = [indexPath indexAtPosition:1];
UITableViewCell* cell = [[UITableViewCell alloc]init];
cell.textLabel.text = [NSString stringWithFormat:@"LABEL%d", index+1];
return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"touch event" message:cell.textLabel.text delegate:nil cancelButtonTitle:@"close" otherButtonTitles:nil];
[alert show];
cell.selected = FALSE;
}

@end


これで、LABEL1~15がリスト表示されて、押されたときに、ダイアログが表示されるようになってます。



これを組み込み。


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];



UIView* oya = [[UIView alloc]init];
oya.frame = CGRectMake(0, 0, 320, 480);
MyTableView* table = [[MyTableView alloc]init];
table.center = CGPointMake(160, 230);
[oya addSubview:table];

UIViewController* vc = [[UIViewController alloc]init];
vc.view = oya;
[self.window setRootViewController:vc];


[self.window makeKeyAndVisible];
return YES;
}



リスト表示
ゆぅさんのiPhone開発技術関連ブログ-その1

押したとき
ゆぅさんのiPhone開発技術関連ブログ-その2