不可能在两个视图控制器之间传递UIImage(没有故事板)

时间:2016-11-20 13:14:52

标签: swift uiviewcontroller uiimageview uiimage

在第一个ViewController(AViewController)中,我设置了相机。捕获图片时,我提供了一个包含UIImageView的其他ViewController(BViewController)。问题是BViewController中的UIImageView没有显示AViewController中捕获的图片。我指定我不使用故事板。

有没有人有想法解决这个失败?我错过了什么 ?谢谢你的帮助!

class AViewController: UIViewController {

  ...

  func capture(){

    if let videoConnection = stillImageOutput!.connection(withMediaType: AVMediaTypeVideo) {
                videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait
                stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(sampleBuffer, error) in
        if (sampleBuffer != nil) {
             let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
             let dataProvider = CGDataProvider(data: imageData as! CFData)
             let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)

             let imageSaved = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right)

             self.present(BViewController(), animated: false, completion: { Void in   
                BViewController().integrate(image: imageSaved)
             })                
        }            
    }
  }
}

=============================================== =================

class BViewController : UIViewController {

   let imageView = UIImageView()

   override func viewDidLoad() {
        super.viewDidLoad()

        imageView.frame = view.bounds
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        view.addSubview(imageView)

   }

   func integrate(image: UIImage){
        imageView.image = image
   }
}

2 个答案:

答案 0 :(得分:2)

我终于用亚特的帮助解决了这个问题:

class AViewController: UIViewController {

   func capture(){
      ...
      let destinationVC = BViewController()
      destinationVC.image = imageSaved
      self.present(destinationVC, animated: false, completion: nil)
   }
}

//=====================================================

class BViewController : UIViewController {

   var image = UIImage()
   let imageView = UIImageView()

   override func viewDidLoad() {
      super.viewDidLoad()

      imageView.frame = view.bounds
      imageView.image = image
      imageView.contentMode = .scaleAspectFill
      imageView.clipsToBounds = true
      view.addSubview(imageView)

   }
}

答案 1 :(得分:0)

self.present(BViewController(), animated: false, completion: { Void in   
    BViewController().integrate(image: imageSaved)
})  

短语BViewController()表示“制作一个全新的视图控制器”。但你说两次!因此,您呈现的视图控制器(第一行)和您将图像提供给第二行的视图控制器是两个完全不同的视图控制器。