我正在用下面的代码来编写一段代码:
-每次点击按钮都会打开一个新视图,并允许用户从手机图库中选择图像。 -所选图像应加载并在水平滚动视图中显示。
我面临的问题是,选择图像时选择器会自动关闭,但是选择器关闭时图像不会加载到UIcollectionView内(占位符图像保留并且未被所选图像替换)。我的控制台没有崩溃或错误。谢谢你的帮助!
这是我针对此功能的视图控制器:
public class ImagePickerViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
var mediaArray = [UIImage]()
@IBAction func galleryButtonTapped(_ sender: Any) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let actionSheet = UIAlertController(title: "Gallery image", message: "Choose an image from your gallery", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { (action: UIAlertAction) in
imagePickerController.sourceType = .photoLibrary
self.present(imagePickerController,animated: true, completion: nil )
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(actionSheet, animated: true,completion: nil)
}
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
mediaArray.append(selectedImage)
picker.dismiss(animated: true, completion: nil)
}
public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return mediaArray.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MediaCollectionViewCell", for: indexPath) as! MediaCollectionViewCell
cell.mediaContent.image = mediaArray[indexPath.row]
return cell
}
}
选择图片获取后,重新加载您的收藏夹视图。
public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
mediaArray.append(selectedImage)
picker.dismiss(animated: true) {
self.collectionView.reloadData()
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句