見出し画像

【Objective-C】UIViewControllerでUITableViewを描画する方法【Xcode10.1】

こういう人に向けて発信しています。
・UITableViewControllerではなく、UIViewControllerでTableViewを描画したい人
・TableViewを表示したい人
・Objective-C初心者

今回使うクラスについて

Projectを新規作成した際にすでに存在している、
・ViewController.h
・ViewController.m

こちらのクラスのみを利用して、なるべくシンプルに作成いたしました。

セクションの設定や、ヘッダーの高さなどのメソッドについて(拡張機能)

セクション数を変動させたりすることはできますが、
一度に詰め込んだりすると分からなくなるので、
今回はシンプルに表示だけに絞ってご紹介いたします。

コード(Objective-C) ViewController.h

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end

コード(Objective-C) ViewController.m

#import "ViewController.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation ViewController{
    //インスタンス変数の宣言 //これにより、このインスタンスのインスタンスメソッドからアクセスが可能になる。
    //各インスタンスメソッドでアクセスする時は tableViewでアクセス可能。
    UITableView *tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //tableViewの初期化
    //initWithFrame(初期化しつつFrame指定している)
    tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
    
    /*
     tableViewにはUITableViewDelegate,UITableViewDataSource 2つのデリゲートが存在しており、
    「delegateを処理するのはこのインスタンス(self)ですよ」と宣言する必要がある。
     */
     tableView.delegate = self;
    tableView.dataSource = self;
    
    //このインスタンスのViewにtabelViewを描画する。
    [self.view addSubview:tableView];
}

#pragma  #UITableView Datasource(実装必須)

//row = 行数を指定するデリゲートメソッド
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //必ずNSInteger型を返してあげている。
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //標準で用意されているTableViewを利用する場合。
     NSString *cellIdentifier = @"Cell";
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
     
     if (!cell) {
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
     }
    
    cell.textLabel.text = [NSString stringWithFormat:@"このセルは%ld番目のセルになります!", (long)indexPath.row];
     return cell;
}

@end


この記事が気に入ったらサポートをしてみませんか?