UIテーブルViewとUIテーブルViewControllerを分離する[Objecitve-C]


UIテーブルViewとUIテーブルViewControllerをうまく切り離す方法に苦労していたので今後のためにメモ。Webだったら簡単な実装でもObjective-Cだと結構つまずます。もう少し入門書を読まないとなぁ。


😀 UIテーブルView.h - ヘッダファイル

@interface tableView : UITableView
@end

🚕 UIテーブルView.m - 実装ファイル

@interface tableView()
@end

@implementation tableView

- (id)init {
self = [super init];

// dataSourceとdelegateの設定
self.dataSource = self;
self.delegate = self;

return self;
}

#pragma mark - セクションの数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}

#pragma mark - セクション内の列の数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}

#pragma mark - セクションタイトル
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
switch(section) {
case 0:
return nil;
break;
}
return nil;
}

#pragma mark - テーブルセルの定義
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}

return cell;
}

#pragma mark - テーブルセルの高さ
-(CGFloat) tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
return 30;
}

#pragma mark - テーブルセルが選択された場合
- (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath {
//....
}

#pragma mark - 背景色の設定
- (void)drawRect:(CGRect)rect {
[[UIColor whiteColor] setFill];
UIRectFill(CGRectInset(self.bounds, 0, 0));
}

🚜 テーブルViewController.m - 実装ファイル

#import "TableView.h"

@implementation TableViewController

-(id) init {
self = [super init];

if (self) {
TableView tableView = [[TableView alloc] init];
self.view = tableView;
}

return self;
}

@end

🐯 あとがき

このあたりはすごく地味だけど、保守しやすいコードを書くために試行錯誤中です。
もし、Objective-Cで正しくコードを書くために知っておいた方がいい情報とかあればぜひメッセージください!

🐞 参考リンク

[MN]UITableViewのテンプレート | Make&Nature

UIViewControllerでUITableViewを使う: iPhoneアプリ開発日記

🖥 VULTRおすすめ

VULTR」はVPSサーバのサービスです。日本にリージョンがあり、最安は512MBで2.5ドル/月($0.004/時間)で借りることができます。4GBメモリでも月20ドルです。 最近はVULTRのヘビーユーザーになので、「ここ」から会員登録してもらえるとサービス開発が捗ります!

📚 おすすめの書籍