从特定的childViewControllers类调用方法

时间:2017-06-06 06:36:16

标签: ios swift swift3

好的,希望我能尽可能清楚地解释这一点。

我有一个Parent ViewController,它有一个ContainerView,它将包含不同的viewControllers / Class。我正在运行时更改此容器的内容,如下所示:

    let newController = (storyboard?.instantiateViewController(withIdentifier: classIdentifierFromStoryboard))! as UIViewController
    let oldController = childViewControllers.last! as UIViewController

    oldController.willMove(toParentViewController: nil)
    addChildViewController(newController)
    newController.view.frame = oldController.view.frame

    transition(from: oldController, to: newController, duration: 0, options: .transitionCrossDissolve, animations:{ () -> Void in
        }, completion: { (finished) -> Void in

    })

    oldController.removeFromParentViewController()
    newController.didMove(toParentViewController: self)

例如,在UI上显示的当前控制器是firstVC,有点像

class firstVC {
    func removeAnnotations() {
        //something that removes annotation from MapVC
     }
}

在父控制器上的某个事件上,如何访问firstVC的实例,以便我能够调用removeAnnotations?截至目前我正在获取nil,在父控制器firstVC.removeAnnotations上使用它,可能这会调用该类的另一个实例。任何帮助都会很棒!希望我的解释有意义。谢谢!

2 个答案:

答案 0 :(得分:0)

您可以像这样运行子视图控制器:

for case let vc as firstVC in self.childViewControllers {
    vc.removeAnnotations()
}

这将运行firstVC类型的所有子视图控制器并执行removeAnnotations方法

答案 1 :(得分:0)

此代码中的

是子视图控制器ProfileViewController

首先创建一个像这样的子视图控制器的对象

 var objectProfile:ProfileViewController!

然后是viewDidLoad方法

 override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        let storyboard = UIStoryboard(name: "Main", bundle: nil)

        objectProfile = storyboard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
        objectProfile.view.frame = CGRect(x:  -(self.view.frame.size.width - 40), y: 0, width: self.view.frame.size.width - 40, height: self.view.frame.size.height)
        self.view.addSubview(objectProfile.view)
        self.navigationController?.didMove(toParentViewController: objectProfile)

        objectProfile.view.isHidden = true

    }

然后按钮点击这里的方法代码

 @IBAction func btnProfilePressed(_ sender: UIButton) {

        UIView.animate(withDuration: 0.3) { 

            self.objectProfile.view.frame = CGRect(x:  0, y: 0, width: self.view.frame.size.width - 40, height: self.view.frame.size.height)


        }

    }

然后touchesBegan

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        objectProfile.view.isHidden = false

        UIView.animate(withDuration: 0.3) {

            self.objectProfile.view.frame = CGRect(x:  -(self.view.frame.size.width - 40), y: 0, width: self.view.frame.size.width - 40, height: self.view.frame.size.height)


       }

    }

完成设置此代码输出是

enter image description here enter image description here