我第一次在这里发布一个带有实际工作代码的问题!但是,我相信有一种方法可以减少代码行数。希望有大神给我指路。
这是供参考的故事板窗口:
我有一个带有 containerView 的主 ViewController。ContainerView 有它自己的导航控制器。主视图控制器左侧的每个按钮 (B1-B5) 与其各自的场景编号相连。即 B2 会将场景 2 推入堆栈。B4 将场景 4 推入堆栈。如果 visibleViewContoller 是场景 5,并且用户按下 B1,它将弹出所有 viewController,直到我们到达场景 1。依此类推。
下面的代码再次运行良好,我只是想缩小 B1 和 B2 的代码大小:
- (IBAction)B1Pressed:(id)sender {
UINavigationController *navController = [self.childViewControllers objectAtIndex:0];
NSMutableArray *VCs = [navController.viewControllers mutableCopy];
UIViewController *visibleViewController = [navController visibleViewController];
if (visibleViewController == [VCs objectAtIndex:0])
{
return;
}
else if (visibleViewController ==[VCs objectAtIndex:1])
{
[navController popViewControllerAnimated:YES];
}
else if (visibleViewController ==[VCs objectAtIndex:2])
{
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:YES];
}
else if (visibleViewController ==[VCs objectAtIndex:3])
{
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:YES];
}
else if (visibleViewController ==[VCs objectAtIndex:4])
{
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:YES];
}
else if (visibleViewController ==[VCs objectAtIndex:5])
{
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:YES];
}
}
- (IBAction)B2Pressed:(id)sender {
UINavigationController *navController = [self.childViewControllers objectAtIndex:0];
NSMutableArray *VCs = [navController.viewControllers mutableCopy];
UIViewController *visibleViewController = [navController visibleViewController];
if (visibleViewController == [VCs objectAtIndex:0])
{
STLMEatDrinkViewController *stlmEDVC = [self.storyboard instantiateViewControllerWithIdentifier:@"B2"];
[navController pushViewController:stlmEDVC animated:YES];
}
else if (visibleViewController ==[VCs objectAtIndex:1])
{
return;
}
else if (visibleViewController ==[VCs objectAtIndex:2])
{
[navController popViewControllerAnimated:YES];
}
else if (visibleViewController ==[VCs objectAtIndex:3])
{
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:YES];
}
else if (visibleViewController ==[VCs objectAtIndex:4])
{
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:YES];
}
else if (visibleViewController ==[VCs objectAtIndex:5])
{
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:NO];
[navController popViewControllerAnimated:YES];
}
}
现在想象为 B3Pressed、B4Pressed 和 B5Pressed 再写 3 次相同的代码。我认为代码太多了,我几乎肯定有更好的方法来解决这个问题。
谢谢你。