2010-01-17 24 views
3

如何使用tableView作为值选择器?如何使用UITableView返回值

所以我有一系列输入字段,当你选择一册田场它打开,你可以从作为该字段的值获取选项的tableview我想是。 选择一个选项后,它将返回到前一个视图,并填充该字段的所选值。

回答

6

这是我做的,类似设置>常规>国际>在iPhone/iPod的语言表视图。

table view 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 

该视图将与presentModalViewController:animated:方法被呈现,以便其从屏幕的底部出现。您可以用任何其他方式呈现它,但它似乎是iPhone应用程序中的标准。

在呈现视图之前,请设置targetselector,以便在用户点击“完成”按钮时调用方法。现在

,在新创建的UITableViewController you can implement the the的tableView: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 
} 

还实现了取消和工具栏按钮做过方法:对于

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

- (IBAction)cancel:(UIBarButtonItem *)item 
{ 
    [self dismissModalViewControllerAnimated:YES]; 
} 
+0

哇非常感谢,真的很好的实现 – Affian 2010-01-17 23:20:35

+0

它适用于我,但当你多次点击同一行时会出现问题。从技术上讲,它始终在同一行添加和删除复选标记,并且您看到的是无选项标记。要解决该问题,只需在tableView:didSelectRowAtIndexPath:if(selectedRow!= indexPath.row){ – Kamel 2014-08-27 07:03:37

1

您应该使用UITableViewDelegatetableView:didSelectRowAtIndexPath:,记住另一个对象(共享实例/单身可能? - 取决于您的体系结构)某处的值,然后关闭此表视图。

1

我实现了一个视图控制器的日期选择。 我创建了一个协议,将选择的日期返回到前一个视图。

@protocol DataViewDelegate 
@optional 
- (void)dataViewControllerDidFinish:(NSDate*)dateSelected; 
@end 

...

- (void) viewDidDisappear:(BOOL)animated 
{ 
    if ([ (id)(self.delegate) respondsToSelector:@selector(dataViewControllerDidFinish:)]) 
    { 
     [self.delegate dataViewControllerDidFinish:self.data]; 
    } 

    [super viewDidDisappear:animated]; 
} 

在选择器查看您可以使用

tableView:didSelectRowAtIndexPath: 

选择您想要的行。在这里我设置数据属性。

上一视图是该协议的委托。