あなたはあなたのアプローチに近づいています。同様の状況で私が行ったことは、個別の UITableViewCell サブクラスを作成し、UISwitch のタグをインデックス パスの index.row に設定し、テーブル ビューの特定のセクションでその UITableViewCell サブクラスのみを使用することです。これにより、セルのタグを使用して、別のインデックス リストを維持することなく、どのセルにイベントがあるかを一意に判断できます (そうしているように聞こえます)。
セル タイプは一意であるため、UITableViewCell サブクラスでメソッド/プロパティを作成することにより、セルの他の要素に簡単にアクセスできます。
例えば:
@interface TableViewToggleCell : UITableViewCell {
IBOutlet UILabel *toggleNameLabel;
IBOutlet UILabel *detailedTextLabel;
IBOutlet UISwitch *toggle;
NSNumber *value;
id owner;
}
@property (nonatomic, retain) UILabel *toggleNameLabel;
@property (nonatomic, retain) UILabel *detailedTextLabel;
@property (nonatomic, retain) UISwitch *toggle;
@property (nonatomic, retain) id owner;
-(void) setLable:(NSString*)aString;
-(void) setValue:(NSNumber*)aNum;
-(NSNumber*)value;
-(void) setTagOnToggle:(NSInteger)aTag;
-(IBAction)toggleValue:(id)sender;
@end
の:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// ... prior iniitalization code for creating cell is assumed
toggleCell.owner = self;
[toggleCell setLable:@"some string value"];
[toggleCell setTagOnToggle:indexPath.row];
toggleCell.owner = self;
return toggleCell;
//... handle cell set up for other cell types as needed
}
所有者はセルのデリゲートであり、コントローラーでアクションを開始するために使用できます。UISwitch の状態が変化したときにデリゲートでアクションを開始できるように、必ず UISwitch を toggleValue アクションに接続してください。
-(IBAction)toggleValue:(id)sender;
{
BOOL oldValue = [value boolValue];
[value release];
value = [[NSNumber numberWithBool:!oldValue] retain];
[owner performSelector:@selector(someAction:) withObject:toggle];
}
メソッド呼び出しで UISwitch を渡すと、セルのインデックス パスにアクセスできます。セルの NSIndexPath を格納する ivar を明示的に設定し、メソッド呼び出しでセル全体を渡すことで、タグ プロパティの使用をバイパスすることもできます。