ios - 尝试在 UICollectionViewCell 类上使用照片库

标签 ios swift uicollectionview uiimagepickercontroller

所以现在我正在尝试让 Collection View 单元格使用照片库来更新照片。这是我的代码:

import UIKit

class viewCellVC: UICollectionViewCell, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var bookImage: UIImageView!
@IBAction func addImage(_ sender: Any) {
    let imagePicker = UIImagePickerController()
    imagePicker.delegate = self
    imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
    imagePicker.allowsEditing = false
    self.window?.rootViewController?.present(imagePicker, animated: true, completion: nil)
}

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

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    let image = info[UIImagePickerControllerOriginalImage] as! UIImage
    bookImage.image = image
    picker.dismiss(animated: true, completion: nil)
}


}

但是,当我尝试运行代码并更新图片时,模拟器无法打开照片库,而是收到以下错误消息(没有结束应用程序,只是无法运行照片库):

2017-08-07 21:35:31.709183-0500 ChuBookElf[2817:66569] Warning: Attempt to present <UIImagePickerController: 0x7f907e0bf800> on <ChuBookElf.ViewController: 0x7f907de072c0> whose view is not in the window hierarchy!

有人可以告诉我我做错了什么吗?我已经研究这个几个小时了。

For Reference, here is what the collection view cell looks like

最佳答案

对于初学者,您将在 UICollectionViewCell 中创建 imagePicker

您应该在包含上述 UICollectionView 以及委托(delegate)方法的 ViewController 中创建 imagePicker。然后,在 didFinishPickingMediaWithInfo 中,将所选图像设置为适当的 collectionViewCell重新加载您的 collectionView

关于ios - 尝试在 UICollectionViewCell 类上使用照片库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45558435/

相关文章:

objective-c - 通过 url 设置 MKPinAnnotationView 图片

ios - 分组的 UITableView 的背景纹理不会随表格滚动

iphone - UITableViewCell 上的 UIPopoverController

android - 使用 Cordova-plugin-facebook4 邀请 Facebook App

ios - 如何在 swift 中使用 SKConstraint

swift - Xcode 项目和 Xcode playground 有什么区别?

ios - UICollectionView 双向滚动

ios - UICollectionView reloadData() 不更新 Collection View 中的单元格

ios - 使用通用 Storyboard : trailing and leading spaces give wrong value 时,将 UIView 设置为使用自动布局更正设备宽度

swift - 判断拖动单元格路径是否==节头路径