2010-01-17 25 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: 

選擇您想要的行。在這裏我設置數據屬性。

上一視圖是該協議的委託。