将数据从自定义 UIView 传递到主 VC



我正在尝试将数据从自定义UI视图传输到MainVC。

在我的自定义视图(这是我的MainVC的一部分)中,我有一个照片集,如果有人选择了他们想要的照片,它应该关闭自定义视图,并使该照片出现在MainVC中。很遗憾,我无法使照片出现在MainVC中。我将如何做到这一点?

在我的自定义 UIView 中,我有以下内容:

  • 在 DidSelectCell 中

    selectedPhotoImage = mediaArray[indexPath.row].image!
    
  • 当一个人选择他们希望该照片是他们希望上传的照片时。

    func chooseScene(gestureRecognizer2: UIGestureRecognizer) {
    let swag = RegisterVC()
    swag.profilePhototoUpload.image = selectedPhotoImage
    }
    

在主VC(即RegisterVC)中,我有以下内容:

let profilePhotoSelction = UIView()
let profilePhototoUpload = UIImageView()
profilePhotoSelction.frame = CGRect(x: self.view.frame.size.width / 17, y: self.view.frame.size.height / 5.2, width: self.view.frame.size.width / 3.4, height: self.view.frame.size.width / 3.4)
profilePhototoUpload.frame = profilePhotoSelction.bounds
profilePhototoUpload.clipsToBounds = true
profilePhototoUpload.layer.cornerRadius = profilePhototoUpload.layer.frame.width / 2

profilePhotoSelction.layer.borderColor = UIColor.black.cgColor
profilePhotoSelction.layer.borderWidth = 2
profilePhotoSelction.layer.backgroundColor = UIColor.rgb(fromHex: 0xa3f323).cgColor
profilePhotoSelction.layer.cornerRadius = profilePhotoSelction.layer.frame.width / 2

let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(RegisterVC.uploadPhoto(gestureRecognizer:)))
gestureRecognizer.delegate = self
profilePhotoSelction.addGestureRecognizer(gestureRecognizer)
profilePhotoSelction.addSubview(profilePhototoUpload)
self.view.addSubview(profilePhotoSelction)

我怎么可能获得个人资料照片上传视图有那个人选择的照片?

执行此操作的最佳方法可能是创建一个RegisterVC将符合的简单protocol,并且当需要将该映像传递回RegisterVC时,您可以使用协议方法。

举个非常简单的例子,你可以这样定义你的protocol

protocol SelectImageDelegate {
func didSelectImage(image: UIImage)
}

然后,在自定义 UIView 中,您需要此委托的变量,如下所示:

let delegate: SelectImageDelegate

您需要将此属性添加到init,以便可以在init期间将RegisterVC设置为delegate

然后,在RegisterVC中,您可以添加到类声明以符合协议,因此它看起来像class RegisterVC: UIViewController, SelectImageDelegate {...

最后,您需要实现协议方法,并执行以下操作:

func didSelectImage(image: UIImage) {
self.profilePhotoToUpload.image = image
//Do whatever else you need with the image here...
}

你可以试试这个方式:

1). 在自定义UIView中定义主VC类型的变量

var mainVC: MainVC? 

2). 从 MainVC 打开自定义 UIView 时,将其新创建的mainVC设置为self

3). 在此视图控制器中添加显示图像的方法,即

func showSelectedImage(image: UIImage) {
....
}

4). 现在从自定义 UIView控制器选择图像后,您将关闭自定义 UIView 从 MainVC 调用该方法,如下所示:

self.showSelectedImage(image:theSelectedImage)

这是解决您的问题的方法之一,当然您也可以使用协议。