思い立ったが吉日!

iOSが好きです。

Storyboardを使ったUITableView

Storyboardを使ったUITableView

なるべくコードを書かずにStoryboardでTableViewが表現されてるソースを見た時、少しハマったのでメモ。

セルがカスタマイズされたテーブルの表示の作成の流れを確認。

まずは、通常通りSingleViewApplicationの作成。

f:id:watarotten:20151126083909p:plain

UITableViewの設置

f:id:watarotten:20151126084147p:plain

UITableViewCellの設置

f:id:watarotten:20151126084335p:plain

設置しただけではセルは反映されません。(わかりやすくするためセルの色を変えてます)

f:id:watarotten:20151126084629p:plain

いつものUITableViewのDelegate等の設定を行うのですが、viewDidLoadではなく、Storyboard上から設定したいと思います。

f:id:watarotten:20151126084951p:plain

ここにDelegateとDataSourceの設定項目があります。

うまく撮影できなかったのですが、DelegateとDataSourceからControl + Drugで黄色アイコンに向かって接続しViewControllerに結びつけます。

f:id:watarotten:20151126085204p:plain

すると、ViewController側ではこのように確認できます。

f:id:watarotten:20151126085403p:plain

次に、セルを設定したいと思います。

CellのContentView内に適当に部品を配置していきます。

Cellの高さはドラッグすれば変更できます。

f:id:watarotten:20151126090939p:plain

カスタムセルのファイルを追加します。

f:id:watarotten:20151126091005p:plain

カスタムセルのひも付けを行います。

f:id:watarotten:20151126091115p:plain

さらに、再利用のためのIdentifierを設定します。

f:id:watarotten:20151126091227p:plain

プロパティをコードに接続しておきます。

f:id:watarotten:20151126092157p:plain

ここからはソースコードになります。

ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>


@end

ViewController.m

#import "ViewController.h"
#import "CustomCell.h"

@interface ViewController ()

@end

@implementation ViewController

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

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



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

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomCell";
    CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    cell.titleLabel.text = @"グッド";
    cell.commentLabel.text = @"これはイイと言う意味です。";
    
    return cell;
}
@end

これを実行すると

f:id:watarotten:20151126092538p:plain

切れてかっこ悪いですが、このようになります。

調整ついでに、TableHeader,TableFooterを付けたいと思います。

f:id:watarotten:20151126093302p:plain

赤がHeaderView,青がFooter View,ピンクがcellのBoarder Viewになります。

Header,FooterはTableViewの中で、Cellの外に配置

f:id:watarotten:20151126093515p:plain

BoaderViewはContentViewの中に配置されていることに注意してください。

Cellの数を2に減らして、実行すると

f:id:watarotten:20151126093658p:plain

このようになります。

セルが表示されいないって人はこれをチェックするといいかもです。

qiita.com