将NSMutableArray detailsDataSource
和int detailIndex
传递给下一个View Controller
MainDetailViewController.m
:
#import "UsersDetailViewController.h"
...
- (void)swipeDetectedUp:(UISwipeGestureRecognizer *)sender
{
UsersDetailViewController *usersController = [[self storyboard] instantiateViewControllerWithIdentifier:@"UsersController"];
[self.navigationController pushViewController:usersController animated:NO];
usersController.usersDataSource = [[NSMutableArray alloc] initWithArray:detailsDataSource];
usersController.userDetailIndex = detailIndex;
}
在UserDetailViewController.m
中轻扫索引:
- (void)swipeDetectedRight:(UISwipeGestureRecognizer *)sender
{
if (userDetailIndex != 0)
userDetailIndex--;
}
当swipeDetectedDown弹回时,MainDataViewController
需要知道要显示索引的对象:
- (void)swipeDetectedDown:(UISwipeGestureRecognizer *)sender
{
//jump to correct object at index, same as current object at index in this view
[self.navigationController popViewControllerAnimated:NO];
}
代码建议?
答案 0 :(得分:0)
使用NSNotificationCenter将对象发送回MainDataViewController ...
示例:
在UsersDetailViewController中,使用key =>值对填充NSDictionary,然后将其发送到您希望的位置。
NSArray *key = [NSArray arrayWithObject:@"myIndex"];
NSArray *object = [NSArray arrayWithObject:detailIndex];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:object forKeys:key];
[[NSNotificationCenter defaultCenter] postNotificationName:@"MainDataViewController" object:self userInfo:dictionary];
注意:您需要在MainDataViewController上设置一个名为MainDataViewController的标识符或任何您想要调用它的标识符。使用VC名称可以使其更简单。
然后在MainDataViewController上,在viewDidLoad()方法中执行此操作。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"MainDataViewController" object:nil];
然后使用以下方法接收通知:
- (void)receiveNotification:(NSNotification *) notification
{
if([[notification name] isEqualToString:@"MainDataViewController"])
{
NSDictionary *dictionary = [NSDictionary dictionaryWithDictionary:[notification userInfo]];
if([dictionary valueForKey:@"myIndex"])
{
// do whatever you need to do with the passed object here. In your case grab the detailIndex and use it for something...
}
}
}
答案 1 :(得分:0)
简单的部分是将UsersDetailViewController指针放入MainDetailViewController的属性中,以便它可以访问self.usersController.usersDataSource& self.usersController.userDetailIndex稍后。然后唯一的技巧就是让用户知道何时弹出UsersDetailViewController。
在我以前编写的代码中,我经常尝试使MainDetailViewController成为UsersDetailViewController的委托,并在UsersDetailViewController想要以编程方式关闭时调用MainDetailViewController中的委托方法,并在其中同时执行popViewControllerAnimated:并更新MainDetailViewController的状态。换句话说,总是让父母的代码弹出孩子。这是有效的,但是如果您通过导航控制器的后退按钮自动弹出子视图控制器,则不会这样,所以总体来说我反对这种技术。
我认为有更好的解决方案可以在弹出子节点时调用父代码。也许实现一个viewWillAppear方法,如果在那里设置了self.usersController,那么你知道你将从UsersDetailViewController返回,此时访问其他控制器的属性,最后清除self.usersController。