You are approaching your approach. What I did in such situations was to create separate subclasses of UITableViewCell, set the UISwitch tag as index.row of the index path, and use this subclass of UITableViewCell only in a specific section of the table view. This allows you to use a cell tag to uniquely determine which cell has an event without supporting a separate index list (as it sounds, as if you are doing).
Since the cell type is unique, you can easily access other elements of the cell by creating methods / properties in a subclass of UITableViewCell.
For example:
@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
IN:
- (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 }
The owner is the delegate for the cell and can then be used to trigger actions in your controller. Make sure you connect your UISwitch to the toggleValue action so that you can trigger actions in the delegate when the UISwitch changes state:
-(IBAction)toggleValue:(id)sender; { BOOL oldValue = [value boolValue]; [value release]; value = [[NSNumber numberWithBool:!oldValue] retain]; [owner performSelector:@selector(someAction:) withObject:toggle]; }
By passing UISwitch by a method call, you can access the pointer path for the cell. You can also get around using the tag property by explicitly having ivar to store the NSIndexPath of the cell, and then pass the entire cell by a method call.
Chip coons
source share