来自UIImagePickerController的选定图像未显示在UIImageView中

时间:2017-08-11 18:57:04

标签: swift uiimageview delegates uiimagepickercontroller

我正在尝试从持有UIImageView的collectionViewCell内的UIImagePickerController中显示所选图像。我可以打开并加载imagePicker,但是当我选择图像时,UIImageView仍然具有硬原始占位符图像。我相信它与将selectedImage传递到实际的单元格有关,而不是与loginController相关,但我不确定。在此先感谢您的帮助!

// loginCell类 class LoginCell:UICollectionViewCell,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

lazy var profileImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.image = UIImage(named: "imagefile")
    //...
    imageView.addGestureRecognizer(UITapGestureRecognizer(target:self, action: #selector(handleSelectProfileImage)))
    imageView.isUserInteractionEnabled = true
    return imageView
}()

var loginController: LoginController?

func handleSelectProfileImage() {
    guard let loginController = delegate as? LoginController else {
        return
    }
    loginController.showImagePicker()
}

}

//登录控制器类 class LoginController:UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,LoginControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

weak var loginCollectionView: UICollectionView!

func showImagePicker() {
    let picker = UIImagePickerController()
    picker.delegate = self
    picker.allowsEditing = true
    present(picker, animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    var selectedImageFromImagePicker: UIImage?

    if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
        selectedImageFromImagePicker = editedImage
    } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
        selectedImageFromImagePicker = originalImage
    }

    if let selectedImage = selectedImageFromImagePicker {
        loginCell.profileImageView.image = selectedImage
    }
    dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    dismiss(animated: true, completion: nil)
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let loginCell = collectionView.dequeueReusableCell(withReuseIdentifier: loginCellId, for: indexPath) as! LoginCell
        loginCell.delegate = self
        return loginCell
}

1 个答案:

答案 0 :(得分:0)

您正在此处创建LoginCell的新实例:

if let selectedImage = selectedImageFromImagePicker {
    let loginCell = LoginCell()
    loginCell.profileImageView.image = selectedImage
}

您应该删除第二行,因此您使用的是名为loginCell的类变量,而不是本地变量,根据您的代码,它不会显示在任何地方。

if let selectedImage = selectedImageFromImagePicker {
    loginCell.profileImageView.image = selectedImage
}