【问题标题】:Can I pass an image on the SecondViewController to the FirstViewController?我可以将 SecondViewController 上的图像传递给 FirstViewController 吗?
【发布时间】:2020-03-15 18:23:41
【问题描述】:

从第一个 ViewController 我按下一个按钮并打开一个查看图像集合的 SecondViewController,当我点击图像时,视图显示全屏图像并返回到集合视图。我可以将图像传递给第一个(启动)视图控制器以将其用作背景吗?


class SecondViewController: UIViewController {
    @IBAction func returnHome(_ sender: UIButton) {
        //self.dismiss(animated: true, completion: nil)
        self.performSegue(withIdentifier: "backToHome", sender: nil)
    }
    var images = ["bg13", "bg11", "bg6", "bg10", "bg12", "bg5", "bg3", "bg4", "bg2", "bg7", "bg8", "bg9", "bg1", "bg14"]
    // ...
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let imageViewCollection = UIImageView(image:UIImage(named: images [indexPath.item]))
        imageViewCollection.frame = self.view.frame
        imageViewCollection.backgroundColor = .black
        imageViewCollection.contentMode = .top
        imageViewCollection.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
        imageViewCollection.addGestureRecognizer(tap)
        imageViewCollection.addGestureRecognizer(tap)
        imageViewCollection.isUserInteractionEnabled = true
        self.view.addSubview(imageViewCollection)
    }      
    @objc func dismissFullscreenImage(_ sender: UITapGestureRecognizer) {
        sender.view?.removeFromSuperview()
    }
}

【问题讨论】:

  • 你应该修复代码。一切都没有包装在代码块中。难以阅读(尤其是在手机上)
  • 不清楚(对我来说)您的导航堆栈是什么。在您的SecondViewController 中,您也在做performSegue...?返回首页?这是一个放松的segue吗?另外,您具体要传递回firstViewController 什么?绝对有一种方法可以使用 segues 来做到这一点。但最后(也是最重要的)——如果第二个 VC 的全部目的是选择第一个 VC 的背景图像,为什么不从第一个 VC 呈现它并使用委托?

标签: swift image collections viewcontroller back


【解决方案1】:

您可以使用 Delegate 将图像传递给第一个视图控制器。 将此协议写在 Second View Controller 的顶部。

protocol SecondViewControllerDelegate: NSObject {
    func sendToFirstViewController(image: UIImage)
}

然后在 Second View Controller 中创建一个变量

class SecondViewController: UIViewController {
    ....
    weak var customDelegate: SecondViewControllerDelegate?
    ....
}

collectionView:didSelectItemAt:indexPath 方法调用它

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let image = UIImage(named: images [indexPath.item])
    customDelegate?.sendToFirstViewController(image: image)
    ...
}

在第一个视图控制器中,在你实例化第二个视图控制器的地方,放置这一行

secondVc.customDelegate = self

然后创建一个扩展来实现委托方法

extension FirstViewController: SecondViewControllerDelegate {
    func sendToFirstViewController(image: UIImage){
        // use this image as your background
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多