首页 > 解决方案 > 从 viewDidDisappear 但不是从按钮 Swift 4 调用函数时出现 Fond nil 错误

问题描述

我有一个我不理解的行为。我有两个动画功能cartItemAnimation()cartItemAnimationHide(). 如果我从 's 按钮调用函数,ShopViewController它们会按预期工作,但如果我cartItemAnimation()从返回ShopViewControllerfrom ItemsDisplayViewController's调用函数,则会viewDidDisapper()出现Found nil错误。 从'scartItemAnimationHide()调用。基本上是一个动画,在加载时会隐藏一个小动画,而在关闭后返回它时会显示它。ShopViewControllerviewWillAppear()imageViewShopViewControllerItemsDisplayViewController

以下是涉及的功能:

ShopViewController 的功能:

func cartItemAnimation() {

        UIView.animate(withDuration: 0.7, delay: 0.9, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: .allowUserInteraction, animations: {
            self.itemAnimationImage.transform = .identity  // Thread 1: Fatal error: Unexpectedly found nil ..
        }) { (success) in
//            self.itemAnimationImage.alpha = 0
        }

    }

    func cartItemAnimationHide() {
//        self.itemAnimationImage.alpha = 0

        UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.7, options: .allowUserInteraction, animations: {
            self.itemAnimationImage.transform = CGAffineTransform.init(translationX: -265 , y: -667)
        }) { (success) in
            self.itemAnimationImage.alpha = 1
        }

    }

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(false)
        if ShopGlobalVariables.dismissCounter ?? 0 <= 0 {
            cartItemAnimationHide()
        }
    }

ItemsDisplayViewController 的功能:

override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(true)
        if ShopGlobalVariables.dismissCounter ?? 0 > 0 {
            let vc = ShopViewController()
            vc.cartItemAnimation()
            ShopGlobalVariables.dismissCounter = 0
        }
    }

ShopGlobalVariables.dismissCounter只是我用来在级联中关闭视图控制器的计数器。

你能明白为什么我在self.itemAnimationImage.transform = .identity网上遇到这个错误,但如果我从按钮调用函数,它会完美地工作吗?像往常一样非常感谢。

标签: iosswift

解决方案


如果您将 ItemsDisplayViewController 显示为 Modal,则可以添加指向 ShopViewController 的指针

class ItemsDisplayViewController: UIViewController {
    weak var shopController: ShopViewController?
    ...

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(true)
        if ShopGlobalVariables.dismissCounter ?? 0 > 0 {
            shopController?.cartItemAnimation()
            ShopGlobalVariables.dismissCounter = 0
        }
    }
}

并且不要忘记在 ShopViewController 中设置对 shopController 的引用:

class ShopViewController: UIViewController {
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let itemController = segue.destination as? ItemDisplayViewController {
            itemController.shopController = self
        }
    }
}

推荐阅读