昨日作ったSearchBarの下にTableViewを出してみる
昨日作ったSearchBarの下にTableViewを出したいので
出してみることにします。
AppDelegateは何も変わりません。
初めTopViewControllerをUITableViewControllerにしてたら
親Viewに直接SearchBarを貼付ける事になってしまい、
TableViewの位置が変更できず、1行目が隠れてしまったので
TopViewControllerにUITableViewを作成し、SubViewとして貼付けます。
TopViewController.h
#import <UIKit/UIKit.h> @interface TopViewController : UIViewController <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource> { UISearchBar *searchBar; UITableView *hotKeywordTableView; NSArray *hotKeywordData; } @property (nonatomic, retain) NSArray *hotKeywordData; @end
TopViewController.m
#import "TopViewController.h" @implementation TopViewController @synthesize hotKeywordData; -(id)init{ self = [super init]; if(self != nil){ hotKeywordData = [[NSArray alloc] initWithObjects:nil]; } return self; } // Implement loadView to create a view hierarchy programmatically, without using a nib. - (void)loadView { [super loadView]; CGRect bounds = [[UIScreen mainScreen] applicationFrame]; searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0.0, bounds.size.width, 48.0)]; searchBar.delegate = self; searchBar.placeholder = @"キーワードを入れてください"; [self.view addSubview:searchBar]; hotKeywordTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0, 48.0, bounds.size.width, bounds.size.height - 48.0)]; hotKeywordTableView.delegate = self; hotKeywordTableView.dataSource = self; [self.view addSubview:hotKeywordTableView]; [hotKeywordTableView reloadData]; } // テーブルのセクションの数を返す -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1; } // テーブルのレコード数を返す -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return [hotKeywordData count]; } // このメソッドはテーブルのレコード数だけループして呼ばれる。 // indexPathにはループのセル番号(0スタート)が入る -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // セルのオブジェクトに付ける名前の文字列を生成する NSString *CellIdentifier = @"HotKeyword"; // HotKeywordと言う名前の再利用可能なセルのオブジェクトを生成する UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; // もし生成されていなかったら、セルのオブジェクト生成する if(cell == nil){ cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } cell.text = [hotKeywordData objectAtIndex:indexPath.row]; return cell; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; } - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } - (void)dealloc { [hotKeywordData release]; [hotKeywordTableView release]; [searchBar release]; [super dealloc]; } @end
こんなん出ました!
テーブル、だいぶ分かってきた!