Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a UITableView to return a value

How would I use a tableView as a value selector?

So I have a series of input fields and what I want is when you select a cetian field it opens a tableview of options that you can pick from as a value for that field. Upon selecting an option it returns to the previous View with the selected value filling that field.

like image 412
Affian Avatar asked Dec 05 '25 10:12

Affian


1 Answers

This is what I do, similar to the Settings > General > International > Language table view in the iPhone/iPod.

table view

The user can tap a row and a check mark will appear. The view is dismissed when "Done" or "Cancel" is tapped.

First, create a UITableViewController that will display your options. Have a toolbar on the top with a Cancel and Done button. Also have these properties:

SEL selector;   // will hold the selector to be invoked when the user taps the Done button
id target;      // target for the selector
NSUInteger selectedRow;   // hold the last selected row

This view will be presented with the presentModalViewController:animated: method so it appears from the bottom of the screen. You could present it in any other way, but it seems kind of standard across iPhone applications.

Before presenting the view, set target and selector so a method will be called when the user taps the "Done" button.

Now, in your newly created UITableViewController you can implement the thetableView:didSelectRowAtIndexPath:` method as:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;  // show checkmark
    [cell setSelected:NO animated:YES];                      // deselect row so it doesn't remain selected
    cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:selectedRow inSection:0]];     
    cell.accessoryType = UITableViewCellAccessoryNone;       // remove check from previously selected row
    selectedRow = indexPath.row;                             // remember the newly selected row
}

Also implement cancel and done methods for the toolbar buttons:

- (IBAction)done:(UIBarButtonItem *)item
{
    [target performSelector:selector withObject:[stringArray objectAtIndex:selectedRow]];
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)cancel:(UIBarButtonItem *)item
{
    [self dismissModalViewControllerAnimated:YES];
}
like image 109
Marco Mustapic Avatar answered Dec 06 '25 23:12

Marco Mustapic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!