ios - 使用 Modal Segue 在两个 VC 之间传递图像

标签 ios uiviewcontroller delegates

我正在尝试在两个 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/

相关文章:

ios - swift 关闭 View 时,屏幕有时会卡住且没有错误

delegates - 使用 C++/CLI 从点击事件调用委托(delegate)

ios - swift ios 核心数据是否具有预填充功能

iOS 更改方向时更改 UI 的最佳方式

memory - 为什么将值设置为 "self"会导致内存泄漏?

ios - UIAlertView 未返回适当的值

ios - 将 UIViewController 更改为 UITableViewController

iphone - 'NSObject<PageControlDelegate>' 没有可见的@interface 声明选择器 'pageControlPageDidChange:'

objective-c - map 查看 :didAddAnnotationViews: doesn't respond

ios - 显示上面有 3D 对象的平铺 map