Swift-保存在segue之后设置的ViewController



此刻我必须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)
}

要在双向传递数据的视图控制器之间移动,需要

  • 一种一致的导航方法:segues通过导航控制器推/弹出,或模式地呈现/消除。但对于一个a-B-a转换,不能混合使用它们

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

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

子类需要与其父类有一个约定的接口,以便进行通信。这是通过协议完成的。在这个例子中,我们为孩子提供了一种将其更新的图像传回父母的方法:

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

然后在子类中创建一个委托变量,该变量可以指向采用该协议的任何类(在这种情况下,该类将是其父类(,然后使用该委托和协议的函数将图像数据传递回。一旦数据通过代理传递回来,视图控制器B调用导航控制器的popViewCntroller方法关闭自身并将焦点返回到视图控制器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(,但在此之前,该类需要符合协议:

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)
}
}

您创建了新的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)
}

最新更新