我正在尝试在两个 VC 之间使用委托(delegate)来传递数据,但我不明白为什么它不起作用。
我的第一个风投
class ViewController: UIViewController {
@IBOutlet weak var profileImage: UIImageView!
func downloadPhoto() {
self.performSegue(withIdentifier: "showPhotoFromInternet", sender: nil)
}
}
extension ViewController: IPresentaionPhotoFormInternetDelegate {
func setNewImage(imageToShow: UIImage) {
profileImage.image = imageToShow
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destination = segue.destination as? PresentPhotoFromInternetViewController {
destination.delegate = self
}
}
我的第二个风投
class PresentPhotoFromInternetViewController: UIViewController {
var imageToSend: UIImage?
var delegate: IPresentaionPhotoFormInternetDelegate?
@IBOutlet weak var photoCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
photoCollectionView.allowsMultipleSelection = false
}
@IBAction func sendPhotoToPreviousController(_ sender: Any) {
delegate?.setNewImage(imageToShow: iamgeToSend!)
performSegue(withIdentifier: "sendPhoto", sender: nil)
}
extension PresentPhotoFromInternetViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! photoCollectionViewCell
print("Cell is selected")
iamgeToSend = cell.photoImageView.image
cell.selectedView.backgroundColor = UIColor.green
}
protocol IPresentaionPhotoFormInternetDelegate {
func setNewImage(imageToShow: UIImage)
}
我从第一个 VC 到第二个 VC 使用现在模态 segue,并从第二个显示到第一个
当我从第二个 VC 执行 segue 时,我的第一个 VC 没有更新,尽管它通过了所有断点。
最佳答案
问题是您没有弹出 Controller ,而是在按钮操作中加载了全新的 Controller
@IBAction func sendPhotoToPreviousController(_ sender: Any) {
delegate?.setNewImage(imageToShow: iamgeToSend!)
//Comment or remove the performSegue
//performSegue(withIdentifier: "sendPhoto", sender: nil)
//Now simply pop this controller
_ = self.navigationController?.popViewController(animated: true)
// If you are presenting this controller then you need to dismiss
self.dismiss(animated: true)
}
注意:如果您认为 segue 是一种Push
,那么使用 popViewController
或者它是一种 Modal
比你需要使用dismiss
。
关于ios - 使用 Modal Segue 在两个 VC 之间传递图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43930175/