以下を使用します。
- (NSInteger) tableView: (UITableView*) tableView numberOfRowsInSection: (NSInteger) section
このデリゲート メソッドは、その特定のセクションに必要な行数を返します。したがって、2 行以上が必要な場合、または行数を動的にしたい場合は、AppDelegate または viewController クラスの init メソッドで NSArray を作成し、次のように numberOfRowsInSection メソッドで数値を返すことができます。
return [delegate numberOfNames];
上記の例では、AppDelegate に配列を作成し、その配列にあるオブジェクトの数を返すメソッドも作成して、テーブルの行数を作成できるようにしました。
- (UITableViewCell*) tableView: (UITableView*) tableView cellForRowAtIndexPath: (NSIndexPath*) indexPath
このデリゲート メソッドは、各セルに表示する内容を表示します。したがって、AppDelegate で作成した配列に続いて、最初にセルを作成し、AppDelegate で作成したメソッドを使用して、セルに表示するテキストを設定します。このメソッドは、NSInteger を取り込みながら NSString を返します。配列をループして、それに応じてテキストを表示できます。
static NSString* MyIdentifier = @"Default";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if( cell == nil )
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];
cell.textLabel.text = [delegate nameAtIndex:indexPath.row];
}
nameAtIndex は、テーブルのすべての項目を格納するために作成した NSArray から特定のインデックス (行番号) で NSString オブジェクトを返す AppDelegate で作成したメソッドの名前です。
ユーザーが作成されたテーブルのいずれかの行をクリックすると、このデリゲート メソッドが呼び出されます。
- (void) tableView: (UITableView*) tableView didSelectRowAtIndexPath: (NSIndexPath*) indexPath
ここでは、表示されたテキストが、項目をテーブルに格納する AppDelegate の配列内の項目のいずれかと一致するかどうかを確認し、必要なビューを作成します。
UIViewController* viewController = nil ;
NSString* nameInArray = [delegate nameAtIndex:indexPath.row] ;
if( [nameInArray isEqualToString:@"firstName"] )
{
viewController = [[FirstViewController alloc] init];
}
else if( [nameInArray isEqualToString:@"secondName"] )
{
viewController = [[SecondViewController alloc] init];
}
else if( [nameInArray isEqualToString:@"thirdName"] )
{
viewController = [[ThirdViewController alloc] init];
}
したがって、これら 3 つのデリゲート メソッドを使用すると、作成された NSArray を使用してテーブルを作成し、ユーザーが選択したテーブルのオプションに従って、ユーザーを viewController にリダイレクトできます。テーブルをセットアップするときに配列のカウントを返すため、テーブルにさらに行を追加することを選択した場合、デリゲート メソッドを編集し続ける必要はありません。
配列と配列のデータを取得するメソッドは、viewController でも作成できますが、必ずしも AppDelegate で作成する必要はありません。
方法は次のとおりです。
-(NSInteger) numberOfNames
{
return [myArray count];
}
-(NSString*) nameAtIndex: (NSInteger) index
{
return [myArray objectAtIndex:index] ;
}
お役に立てれば!:)