e.g. RootViewController 是一TableViewController,將Cell的值傳入DetailViewController。然後,在DetailVC 的TextView編輯好的資料,在回傳入RootViewController上頭的Cell,改變Cell 的值.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
RootViewContrller.h 裡要設一 NSDictionary *returnSelection; 來接收回傳的值
RootViewController.m:
//傳資料到DetailController
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
UIViewController *destination = segue.destinationViewController;//將segue的目的控制器指定給destination
//第一個if是回傳時用的
if ([destination respondsToSelector:@selector(setDelegate:)]) { //如果對setDelegate:方法有反應,便將自己存成value,設key為delegate
[destination setValue:self forKey:@"delegate"];
}
//第二個if是傳出用的
if ([destination respondsToSelector:@selector(setMySelection:)]) {//如果對setSelection:方法有反應,請準備處理選擇後的值
//prepare selection info
NSIndexPath *indexPath = [self.table indexPathForCell:sender];//將選擇的行列指定給indexPath
id object = [self.arr objectAtIndex:indexPath.row];//取出入徑索引的物件,指定予object
NSDictionary *mySelection = [NSDictionary dictionaryWithObjectsAndKeys:indexPath, @"indexPath", object, @"object", nil]; //將其入徑索引和物件存入到一個dictionary
[destination setValue:mySelection forKey:@"mySelection"];//設定下一個控制器的KVC
}
}
//Setter: 取得來自DetailController的回傳delegate
- (void) setReturnSelection:(NSDictionary *)dict {
if (![dict isEqual:returnSelection]) {
returnSelection = dict;
NSIndexPath *indexPath = [dict objectForKey:@"indexPath"];
id newValue = [dict objectForKey:@"object"];
[tasks replaceObjectAtIndex:indexPath.row withObject:newValue];
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
+++++++++++++++++++++++++++++++++++++++
DetailViewContoller.h 要設 id delegate;
DetailViewController.m
//接收root傳來的值
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *voc = [mySelection objectForKey:@"object"];
}
//回傳到root:
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([delegate respondsToSelector:@selector(setReturnSelection:)]) {
//finish editing
[textView endEditing:YES];
//prepare selection info
NSIndexPath *indexPath = [mySelection objectForKey:@"indexPath"];//回傳到正確的Cell Row
id object = textView.text;
NSDictionary *returnSelection = [NSDictionary dictionaryWithObjectsAndKeys:indexPath, @"indexPath", object, @"object", nil];
[delegate setValue:returnSelection forKey:@"returnSelection"];
}
}
*******************************************************
********************************************************
Xcode 的樣板
這裡的 data 只是單存的 array:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSDate *object = [_objects objectAtIndex:indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}