目前,我有一个包含 UIScrollView
的 ViewController 类,在 ScrollView 中我有另一个 View Controller ,我当前可以在其中接收手势识别。我的目标是能够根据我点击的 subViewController 执行到不同 View Controller 的 Segue。
let scrollView = UIScrollView(frame: CGRect(x:0,y:0, width: self.view.frame.width, height:self.view.frame.height-106))
scrollView.delegate = self;
self.view.addSubview(scrollView);
let subView11 = subView(nibName: nil, bundle: nil);
subView1.view.frame = CGRect(x:0,y:0, width: self.view.frame.width, height: CGFloat(openReelHeight));
self.addChildViewController(subView1);
scrollView.addSubview(subView1.view);
subView.didMove(toParentViewController: self);
然后在子View类中我有一个基本的触摸识别功能:
@IBAction func tapOnView(_ sender: UITapGestureRecognizer) {
//change main View controller
}
最佳答案
我建议让家长执行segue。因此,您需要一种机制来让子级通知父级按钮已被点击。这里有两种方法:
subview Controller 可以定义一个协议(protocol),然后让按钮的
@IBAction
在父 View Controller 中调用该协议(protocol)。protocol ChildViewControllerDelegate { func child(_ child: ChildViewController, didTapButton button: Any) } class ChildViewController: UIViewController { @IBAction func didTapButton(_ sender: Any) { if let parent = parent as? ChildViewControllerDelegate { parent.child(self, didTapButton: sender) } } }
显然,父 View Controller 需要遵守该协议(protocol):
extension ViewController: ChildViewControllerDelegate { func child(_ child: ChildViewController, didTapButton button: Any) { // now segue to whatever you want } }
您也可以遵循显式协议(protocol)委托(delegate)模式,而不是依赖于
父级
的 View Controller 包含关系:protocol ChildViewControllerDelegate: class { func didTapButton(_ sender: Any) } class ChildViewController: UIViewController { weak var delegate: ChildViewControllerDelegate? @IBAction func didTapButton(_ sender: Any) { delegate?.didTapButton(sender) } }
然后,当父级添加子级时,必须显式设置
委托(delegate)
:let child = storyboard!.instantiateViewController(withIdentifier: "ChildViewController") as! ChildViewController addChildViewController(child) child.delegate = self // add the child's view to your view hierarchy however appropriate for your app child.didMove(toParentViewController: self)
当然,父级也必须遵守此协议(protocol):
extension ViewController: ChildViewControllerDelegate { func didTapButton(_ sender: Any) { // segue to next scene } }
请注意,使用这两种方法,您可以更改协议(protocol)的 func
以包含您想要的任何参数(例如,传回某些 UITextField
或其他内容的内容)。同样,您可以使用方法名称来使子函数的功能意图更加明确。我使用了一些通用的方法和协议(protocol)名称,因为我不知道各个 child 在做什么。
关于ios - 从子 ViewController 执行 segue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43965817/