note


iOS XcodeのStoryboardでTable Viewのカスタムセル

iOSプログラミング、1日取り組んでみて、ようやくビギナーからアマチュアになった気がします。

StoryboardでTable Viewのカスタムセルを作って、表示させるやり方。
メモ。

(1) プロジェクト新規作成して、UIViewController上にTable Viewを、その上にTable View Cellを追加。UITableViewControllerを使う場合はここは省略できます。

Pasted Graphic




(2) セル上に好きな部品を配置。後でこのセルを呼び出すために、Table View CellのIdentifierを設定します(下図ではhelloCell)。

Pasted Graphic 1

セルの中の各要素に後でアクセスするために、各
ViewにTagを設定。下図ではLabelに”1”のTagを設定してます。

Pasted Graphic 2

もう一個セルを追加してみる。セルの追加は、Table View Cellをドラッグ&ドロップ。2つ目のセルにもIdentifierを設定。部品を適当に配置。

Pasted Graphic 3





(3) Table Viewをソースコードに紐付け。Table ViewでCtrl押しながらうにょ〜と.h に登録。

Pasted Graphic 4




(4) 後はコードを書くだけ。

[ViewController.h]

#import

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>{

}

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@end




[ViewController.m]


#import "ViewController.h"


@implementation ViewController
@synthesize myTableView;

- (
void)viewDidLoad
{
[
super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

[
myTableView setDataSource:self];
[
myTableView setDelegate:self];
}

- (
void)didReceiveMemoryWarning
{
[
super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}


#pragma mark - Table view data source

- (
NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1; //とりあえずセクションは1
}

- (
NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return 2; //とりあえず2行だけ表示する
}

- (
UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

UITableViewCell *cell;

if(indexPath.row==0){ //0行目のセル
//カスタムセルを選ぶ
cell = [
myTableView dequeueReusableCellWithIdentifier:@"helloCell"];

//各要素にはタグでアクセスする
UILabel *idLabel = (UILabel*)[cell viewWithTag:1];
idLabel.
text = @"Bye";

}
else if(indexPath.row==1){//1行目のセル
cell = [
myTableView dequeueReusableCellWithIdentifier:@"switchCell"];
}

return cell;
}

@end




実行するとこんな感じ。
iOS Simulator Screen shot 2013.02.22 15.36.46