如何从imagePickerController中选择照片后更改标题单元格中的imageView?

时间:2018-04-04 19:47:10

标签: ios swift uiimagepickercontroller

我在集合视图中有一个自定义标题单元格。以下是我在标题中设置我的图片的方式

    let profileImage: UIImageView = {
    let image = UIImageView()
    image.contentMode = .scaleAspectFill
    image.layer.cornerRadius = 42
    image.layer.masksToBounds = true
    return image
}()

    var userInfo: CauNguyenUserInfoModel?{
    didSet{
        if let profileImageUrl = userInfo?.profileImageUrl {
            if let imageUrl = URL(string: profileImageUrl) {
                profileImage.sd_setImage(with: imageUrl, placeholderImage: #imageLiteral(resourceName: "default_avatar"), options: [.continueInBackground, .progressiveDownload], completed: nil)
            }
        }
    }
}

然后我使用协议和委托将动作从我的标题类中的按钮传递到集合视图类,并使用UIImagePickController从用户设备中选择不同的图像

这是来自我的集合View控件的func而不是来自header class

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

并使用此功能获取图像文件

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
        print(editedImage)
    }
    dismiss(animated: true, completion: nil)
}

我的问题是,当用户从他的设备中选择一个图像并且我有图像文件后,如何使用该图像更改标题类中的图像?我把picker func放在我的集合视图控制器中。

1 个答案:

答案 0 :(得分:0)

你走了。

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
    var newImage: UIImage?
    if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
        newImage = editedImage
    } else if let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        newImage = originalImage
    }
    imageView.image = image
    picker.dismiss(animated: true)
}