Swift - 在 segue 之后保存 ViewController 设置

Swift - save ViewController set up after segue

目前我必须ViewControllers。您可以使用 show-seguesViewControllerAViewControllerB 之间切换。问题是每次我切换回来时,ViewControllers 状态都会被重置。如何保存 ViewController 的设置?

从A到B

    @IBAction func editButtonTapped(_ sender: Any) {
    let imageCollectionView = self.storyboard?.instantiateViewController(withIdentifier: "ImageCollectionVC") as! ImageCollectionViewController

    self.navigationController?.pushViewController(imageCollectionView, animated: true)
}

从 B 到 A

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    tappedImage = images[indexPath.row]
    performSegue(withIdentifier: "backToPopUpView", sender: self)

}

您创建了新的 ViewControllerA,结果如下 A -> B -> A。 但事实并非如此,你应该关闭 ViewControllerB...

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    tappedImage = images[indexPath.row]
    self.dismiss(animated: true, completion: nil)
    //performSegue(withIdentifier: "backToPopUpView", sender: self)

}

要在以两种方式传递数据的视图控制器之间移动,您需要一些东西

  • 一致的导航方法:seguespushing/popping 通过导航控制器或模态 presenting/dismissing,但不能将它们混合用于一个 A - B - A 转换

  • protocols/deleagtes 允许数据从子级传递回父级。

在下面的示例中,导航是通过导航控制器进行的,图像用作如何将数据传回父级的示例。将其适应其他情况应该是微不足道的。

子项 class 需要与其父项达成一致的接口以允许其进行通信。这是通过协议完成的。在此示例中,我们为子级提供了一种将其更新后的图像传回父级的方法:

protocol ClassBDelegate {
    func childVCDidComplete(with image: UIImage?)
}

然后在子 class 中创建一个委托变量,它可以指向任何采用协议的 class(在本例中将是其父协议),然后使用该委托和协议的函数将图像数据传回。一旦数据通过委托传回,视图控制器 B 调用导航控制器的 popViewCntroller 方法来关闭自身并 return 聚焦到视图控制器 A

class B: UIViewController {
    var delegate: ClassBDelegate?

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        tappedImage = images[indexPath.row]
        delegate?.childVCDidComplete(with: tappedImage)
        navigationController?.popViewController(animated: true)
    }
}

为了使这一切正常工作,需要将子视图控制器的委托设置为指向其父视图控制器 (A),但在此之前 class 需要遵守协议:

extension A: ClassBDelegate {}
    func childVCDidComplete( with image: UIImage?) {
        self.image = image
    }
}

现在,在实例化子视图控制器时,父视图控制器将自己设置为委托,从而完成通信循环。

Class A: UIViewController {
    var image: UIImage?

    @IBAction func editButtonTapped(_ sender: Any) {
        let imageCollectionView = self.storyboard?.instantiateViewController(withIdentifier: "ImageCollectionVC") as! ImageCollectionViewController
        imageCollectionView.delegate = self
        self.navigationController?.pushViewController(imageCollectionView, animated: true)
    }
}