Swift iOS -In ViewWIllAppear如何在切换标签或视图被打开/关闭时检查是否呈现或关闭了ImagePicker?

时间:2017-07-24 20:00:55

标签: ios swift uiimagepickercontroller dismiss viewwillappear

我有一个tabBarController,其中一个标签是一个名为view2的视图。在view2中有一些在viewWillAppear中运行的代码。我在view2中也有一个UIImagePickerController。

fileprivate var imagePicker = UIImagePickerController()

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        runSomeCode()
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
           imageView.image = image
           imagePicker.dismiss(animated: true, completion: nil)
        }
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    imagePicker.dismiss(animated: true, completion: nil)
}

我意识到每次出现imagePicker然后被解雇然后在viewWillAppear中运行runSomeCode()。我不希望它继续被召唤。

我最初使用下面的代码,但我意识到viewWillAppear中的代码仅在推送view2时才会运行。如果我切换标签并返回它就不会运行。

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

       if (isMovingToParentViewController) || (isBeingPresented){

           runSomeCode()
       }else{
           //runs when switching tabs but also runs after the imagePicker is dismissed
       }
}

如何检查imagePicker是否正在显示或解除,以便我的viewWillAppear中的代码不会运行?

2 个答案:

答案 0 :(得分:1)

This answer通过实施UITabBarControllerDelegate解决了类似的问题。

答案 1 :(得分:1)

即使接受了如此链接的答案,我发现了一些更容易的东西。根据接受的答案,您必须检查视图是否正在按下并且使用bool值和TabBarDelegates通过制表符开关显示它。它有效,但它做了很多工作。我主要担心的是在imagePicker被呈现或被解雇时代码没有运行。

在viewWillAppear中显示此imagePicker测试runSomeCode()仅在视图被推入时运行,并且如果有一个选项卡从另一个选项卡切换回此视图但是如果imagePicker正在运行则不会运行提出或驳回:

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

       if imagePicker.isBeingDismissed == false{

           runSomeCode()
       }
}

以下是在viewWillDisappear中获得相同效果的方法。 runSomeCode()仅在弹出视图时运行,并且如果从该视图到另一个选项卡有一个制表符切换但是如果正在呈现或解除imagePicker则不会运行::

override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

       if imagePicker.isBeingPresented == false{

           runSomeCode()
       }
}