我有兩個視圖控制器:ViewControllerA
和ViewControllerB
。 ViewControllerA
被添加到一個容器視圖,它有按鈕。點擊按鈕時,ViewControllerB
應取代ViewControllerA
。我怎樣才能做到這一點?問題在於該按鈕位於ViewControllerB
之內,而不在主視圖控制器中。在同一個容器視圖中從一個視圖控制器切換到另一個視圖
主要ViewController
:
class ViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
weak var currentViewController: UIViewController?
override func viewDidLoad() {
self.currentViewController = self.storyboard?.instantiateViewController(withIdentifier: "Verify")
self.currentViewController!.view.translatesAutoresizingMaskIntoConstraints = false
self.addChildViewController(self.currentViewController!)
self.initializeFirstScreen(subView: self.currentViewController!.view, toView: self.containerView)
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func initializeFirstScreen(subView:UIView, toView parentView:UIView){
parentView.addSubview(subView)
var viewBindingDict = [String: AnyObject]()
viewBindingDict["subView"] = subView
parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[subView]|", options: [], metrics: nil, views: viewBindingDict))
parentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[subView]|", options: [], metrics: nil, views: viewBindingDict))
}
func switchToValidate(){
let newViewController = self.storyboard?.instantiateViewController(withIdentifier: "Validate")
//this line throws error
//fatal error: unexpectedly found nil while unwrapping an Optional value
newViewController!.view.translatesAutoresizingMaskIntoConstraints = false
self.addChildViewController(newViewController!)
initializeFirstScreen(subView: (newViewController?.view)!, toView: self.containerView)
}
}
ViewControllerA
:
class VerifyViewController: UIViewController {
let mainViewController = ViewController()
@IBAction func VerifyNumber(){
self.switchScreens()
}
func switchScreens(){
mainViewController.switchToValidate()
}
}
switchToValidate
引發以下錯誤:
fatal error: unexpectedly found nil while unwrapping an Optional value
我們需要一些代碼來幫助您 – pierreafranck
試試這個,讓我知道。 self.currentViewController = self.storyboard?.instantiateViewController(withIdentifier:「Verify」)as! VerifyViewController self.currentViewController.mainViewController = self –
這部分內容不清楚self.currentViewController.mainViewController = self currentViewController沒有mainViewController – kosas