Chris Brandt
Chris Brandt

Reputation: 948

How to access UITableView subview selection?

I've created a UIViewController (AnestDrugCalcViewController) that has a button that opens a UITableViewController (DrugTableViewController) to select a drug. The DrugTableViewController is populated based on a NSMutableArray and is made up of several NSDictionary objects (drugName, drugDose, drugConcentration, etc.).

I'm able to open DrugTableViewController by pushing it onto the navigation stack, but I can't figure out how to tell from my AnestDrugCalcViewController what the properties of the selected item are.

//  DrugTableViewController.h
#import <UIKit/UIKit.h>

@interface DrugTableViewController : UITableViewController {
NSMutableArray          *drugList;
NSIndexPath *lastIndexPath;
IBOutlet UITableView    *myTableView;
NSObject *selectedDrug;
}

@property (nonatomic, retain) NSArray *drugList;
@property (nonatomic, retain) UITableView *myTableView;
@property (nonatomic, retain) NSObject *selectedDrug;

@end

Top of DrugTableViewController.m #import "DrugTableViewController.h"

@implementation DrugTableViewController

@synthesize drugList,myTableView, selectedDrug; 

Upvotes: 3

Views: 2638

Answers (2)

rpetrich
rpetrich

Reputation: 32326

UITableView's -indexPathForSelectedRow method will allow you to determine which row is selected:

NSIndexPath *selectionPath = [vwDrugTable indexPathForSelectedRow];
if (index) {
    NSLog(@"Selected row:%u in section:%u", [selectionPath row], [selectionPath section]);
} else {
    NSLog(@"No selection");
}

To be notified when the selection changes, implement tableView:didSelectRowAtIndexPath: in your table view delegate:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Selection Changed");
}

Upvotes: 3

Marc W
Marc W

Reputation: 19241

You could have a property in vwDrugTable that stores the the selected row when the user selects it. Then, after that table view is removed and you are back in vwCalc, just get the data from that property.

So that means in vwDrugTable, have something like this:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.selectedDrug = [self.drugs objectAtIndex:indexPath.row];
}

Then just access selectedDrug from vwCalc when you need it.

Upvotes: 3

Related Questions