ささブログ

この人は心が少年ジャンプなんだ、と言われた。そうだよ。いいじゃん。これからもずっとな!!

Home » スマートフォンアプリ開発 » 【Xcodeメモ】(011) テーブルの追加(UITableViewの場合)

【Xcodeメモ】(011) テーブルの追加(UITableViewの場合)

calendar

reload

【Xcodeメモ】(011) テーブルの追加(UITableViewの場合)

1.storyboad上で、TableViewをドラッグ&ドロップする。

140518-0002

2.ViewController.hにTableViewのpropertyを追加する。property名はtbl_MyTableにした。

140518-0005
140518-0007

3.UIViewControllerに<UITableViewDelegate, UITableViewDataSource>デリゲートを追加。

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tbl_MyTable;

@end

4.警告が2つでる。UITableViewDataSourceの@requiredが2つある為。
140518-0008

↓当該メソッドは、この2つ。

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; →テーブルの件数を返すメソッド。 – (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; →テーブルの各セルオブジェクトを返すメソッド。


5.当該@requiredメソッドを2つViewController.mに追加する。処理内容は一旦、仮で記述。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

return 0;

}

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

return nil;

}

6.テーブルデータを格納するdataSource(property)を定義する。

@property (nonatomic, strong) NSArray *dataSource; // テーブルデータを格納する

7.デリゲート指定、及びdataSourceの値を設定する。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    /* UITableViewDelegate、dataSourceのデリゲートを指定 */
    self.tbl_MyTable.delegate = self;
    self.tbl_MyTable.dataSource = self;
    
    self.dataSource = @[@"1行目", @"2行目",@"3行目"]; // テーブルデータを設定
}

8.先ほどのnumberOfRowsInSection、cellForRowAtIndexPathを実装する。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *CellIdentifier = @"cell"; // CellのIDをつける(意味がわかりませんが、なにコレ??。)
    
    // Cellを取得
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // ↓Cellが存在しない場合は、Cellを生成(??? 最初から作ればいいじゃん?)
    if (!cell) {
    
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:CellIdentifier];
    }
    
    // CellにdataSourceの値を設定
    cell.textLabel.text = self.dataSource[indexPath.row];
    
    return cell;
}

  ↓実行結果

140518-0009

おわり。  

応援嬉しいです^^ にほんブログ村 IT技術ブログ iPhoneアプリ開発へ

この記事を読んだ方はこの記事も読まれています

この記事をシェアする

コメント

コメントはありません。

down コメントを残す