大家好,我想到了几个解决方案,但对它们不是很满意,所以需要一些想法。
我有:
- 3 个 UIView 实例 view1、view2、view3
- 1个UIViewController实例,存储view1,view2,view3的UIViewController1
我要:
- 在 view1 中放置一个方法,告诉 UIViewController1 切换到 view2。
我是否需要在 view1 中传递对 UIViewController1 的引用?这是唯一正确的方法吗?
最佳答案
首先,这些是全屏 View 吗?如果是这样,您应该考虑拥有 3 个 View Controller ,每个 View 一个,并可能将它们安装在 UITabBarController 中,这与您描述的行为类似。但无论如何:
不, View 不应该告诉 Controller 做任何事情。
在 MVC 架构中, View 呈现信息并接收(某些)用户交互。 Controller 有责任决定如何处理该操作。
View 所做的是告诉 Controller 交互已经发生。
所以您的主要问题是 - 什么事件会产生这种行为?
它是一个按钮吗?按钮(UIControl 的子类)使用目标-操作模式来处理此通信。您的 View 应提供对按钮的引用:
@property (nonatomic, retain) UIButton *switcherButton;
接下来,您将在 View Controller 中实现一个方法:
-(void)viewSwitcherButtonTapped:(id)sender;
这就是您的 View 如何告诉 Controller 一个 UI 事件发生了。这就是它应该做的。由 Controller 根据模型中的状态信息,或根据其自身的内部状态或逻辑来决定点击该按钮时应该发生什么。
最后,在创建 View 之后, Controller 会将自己挂接到按钮上:
[view.switcherButton addTarget:self action:@selector(viewSwitcherButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
这样任何 View Controller 都可以使用这个 View ,并且 View 不依赖于对 Controller 的引用(因为它不应该)。
但按钮只是一个示例,如果生成行为的事件不同,您的实现可能会有所不同。回答那个问题,也许我可以修改这个答案来应用。
你应该看看
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaDesignPatterns/CocoaDesignPatterns.html 中的“模型- View - Controller 设计模式”、“目标- Action 机制”和“委派”
关于iphone - 在没有界面生成器的情况下使用 UIViewController 和 UIViews 切换 View 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5976726/