我目前有两个简单的类,一个是容器视图控制器,另一个是子视图控制器。我在ContainerViewController.swift文件中有一个动作,但需要在HomeViewController.swift文件中调用它。我显然不能只拨打ContainerViewController.presentDetailController(self)
,所以我该如何处理?
ContainerViewController.swift
import UIKit
class ContainerViewController: UIViewController {
var currentDetailViewController: UIViewController?
override init() {
super.init()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience init(viewController: UIViewController) {
self.init()
currentDetailViewController = viewController
self.presentDetailController(viewController)
}
override func viewDidLoad() {
super.viewDidLoad()
var homeViewController: HomeViewController = HomeViewController.alloc()
self.presentDetailController(homeViewController)
}
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() }
func presentDetailController(detailViewController: UIViewController) {
if((self.currentDetailViewController) != nil) {
self.removeCurrentDetailViewController();
}
self.addChildViewController(detailViewController)
detailViewController.view.frame = self.frameForDetailController()
self.view.addSubview(detailViewController.view)
self.currentDetailViewController = detailViewController
detailViewController.didMoveToParentViewController(self)
}
func removeCurrentDetailViewController() {
self.currentDetailViewController?.willMoveToParentViewController(nil)
self.currentDetailViewController?.view.removeFromSuperview()
self.currentDetailViewController?.removeFromParentViewController()
}
func frameForDetailController() -> CGRect {
var detailFrame: CGRect = self.view.bounds
return detailFrame
}
}
HomeViewController.swift
import UIKit
class HomeViewController: UIViewController {
func initView () {
self.view.backgroundColor = UIColor.redColor()
var button: UIButton = UIButton(frame: CGRectMake(20, 20, 50, 50))
button.backgroundColor = UIColor.greenColor()
button.addTarget(self, action: Selector("ContainerViewController.presentDetailController(self)"), forControlEvents: UIControlEvents.TouchDown) // This results in a fatal error!
self.view.addSubview(button)
}
override func viewDidLoad() {
super.viewDidLoad()
initView();
}
}
答案 0 :(得分:0)
我认为我们只能通过使用委托将消息传递回父视图控制器。可能还有其他方式,但这是唯一优雅的方式。
方法 - 1
1)
在父视图控制器中创建协议并实现
@interface ParentController : UIViewController <NaviagationDelegate>
@implementation ParentController
//implement method here
//{
// your action in parent controller
//}
2)
现在使用NaviagationDelegate
@property (nonatomic, weak) id <NaviagationDelegate> navigationDelegate;
在子控制器的事件操作上调用委托方法
//Button action method
{
[self.navigationDelegate setText:@"action"];
}
3) 在父视图控制器中将子控制器的委托属性初始化为self
prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.destinationViewController isKindOfClass:[ChildContoller class]])
{
[segue.destinationViewController setNavigationDelegate:self];
}
}
方法 - 2
通过检查从self.navigationController.viewControllers
到parentController类的所有控制器来获取父控制器的引用。