将 UIImageView 从模态设置到另一个控制器

Set UIImageView From Modal To Another Controller

我有一个用户正在填写的表格,我提供了一个带有图像的模式供他们选择。我试图从模式中在原始控制器中设置一个 UIImage,但问题是它是零。

最好的设置方法是什么? viewDidLoad 似乎不会在解除模态时触发,这就是我摆脱它的方式,viewWillAppear 也不会。什么时候可以设置图片?

我现在的代码:

    //Collection view choosing deal background
    @IBOutlet var collectionView: UICollectionView!
    var chosenNumber: Int?

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

        if(self.restorationIdentifier == "NewDeal") {
            if(chosenNumber != nil) {
                newDealBackgroundImage.image = UIImage(named: "food_\(chosenNumber!)")
            }
        }
    }

extension BusinessOwnerVC: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        collectionView.deselectItem(at: indexPath, animated: true)

        //self.newDealBackgroundImage.image = UIImage(named: "food_\(indexPath.row + 1)")!
        chosenNumber = indexPath.row + 1

        self.dismiss(animated: true, completion: nil)
    }
}

如果您的演示风格是 fullScreen … 那么您的 willAppear 将被调用

navigationController.modalPresentationStyle = .fullScreen

但如果您不想要全屏演示,请让自己成为演示控制器的委托并覆盖 presentationControllerDidDismiss(_:)。

class ViewController: UIViewController {

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

        @IBAction func show(_ sender: Any) {
            let newViewController = NewViewController()
            //set delegate of UIAdaptivePresentationControllerDelegate to self
            newViewController.presentationController?.delegate = self
            present(newViewController, animated: true, completion: nil)
        }
    }

    extension UIViewController: UIAdaptivePresentationControllerDelegate {
        public func presentationControllerDidDismiss( _ presentationController: UIPresentationController) {
            if #available(iOS 13, *) {
                //Call viewWillAppear only in iOS 13
                viewWillAppear(true)
            }
        }
    }

经过多次试验,以下是我发现适合我的方法。我想要的只是在我呈现的模式下访问和更新视图控制器(同类)。原来我之前的 VC 仍然有效,所以我所要做的就是将对 VC 的引用传递到模态中,然后我可以更改它的属性。

let modal = UIStoryboard.init(name: "BusinessOwner", bundle: nil).instantiateViewController(withIdentifier: "DealBackgroundSelection") as! BusinessOwnerVC

modal.newDealView = self // This is a weak var of BusinessOwnerVC? declared in the view controller itself

present(modal, animated: true, completion: nil)

然后当我准备关闭该模态时:

self.newDealView!.updateDealImage(number: indexPath.row + 1)

updateDealImage 只是我创建的一个函数来处理所有更新。这对我有用。