如何使用UITableView返回值

Aff*_*ian 3 iphone objective-c uitableview

我如何使用tableView作为值选择器?

所以我有一系列输入字段,我想要的是当你选择一个cetian字段时,它会打开一个选项的tableview,你可以从中选择该字段的值.选择一个选项后,它将返回上一个视图,并且所选值填充该字段.

Mar*_*pic 6

这就是我所做的,类似于iPhone/iPod中的设置>常规>国际>语言表视图.

表视图http://i48.tinypic.com/15sanh3.jpg

用户可以点击一行并显示复选标记.点击"完成"或"取消"时,视图将被取消.

首先,创建一个UITableViewController将显示您的选项.顶部有一个带有"取消"和"完成"按钮的工具栏.还有这些属性:

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
Run Code Online (Sandbox Code Playgroud)

此视图将与presentModalViewController:animated:方法一起显示,以便从屏幕底部显示.您可以以任何其他方式呈现它,但它似乎是iPhone应用程序的标准.

呈现视图之前,设定targetselector因此当用户轻击"完成"按钮的方法将被调用.

现在,在你新创建的UITableViewController you can implement the thetableView:didSelectRowAtIndexPath:`方法中:

- (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
}
Run Code Online (Sandbox Code Playgroud)

还可以为工具栏按钮实现取消和完成方法:

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

- (IBAction)cancel:(UIBarButtonItem *)item
{
    [self dismissModalViewControllerAnimated:YES];
}
Run Code Online (Sandbox Code Playgroud)