I want to show images selected from gallery into an ImageView which is in CollectionView. How do I do this??
Showing selectedImage in normal ImageView is working fine.
Below is my code:
var selectedImage = UIImage ()
#IBAction func selectPics(_ sender: Any)
{
if self.picsCollectionView.isHidden == true
{
self.picsCollectionView.isHidden = false
self.imageView.isHidden = true
}
self.picker.allowsEditing = true
self.picker.sourceType = .photoLibrary
present(self.picker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info:[String: Any])
{
if let image = info[UIImagePickerControllerEditedImage] as? UIImage
{
selectedImage = image
}
else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
selectedImage = image
}
else
{
print("Something went wrong")
}
self.dismiss(animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! UploadCollectionViewCell
cell.cellImgView.image = selectedImage
return cell
}
Found an answer. Needed to add just one line.
Below is the solution:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info:[String: Any])
{
if let image = info[UIImagePickerControllerEditedImage] as? UIImage
{
selectedImage = image
self.picsCollectionView.reloadData()
}
else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
selectedImage = image
self.picsCollectionView.reloadData()
}
else
{
print("Something went wrong")
}
self.dismiss(animated: true, completion: nil)
}
Related
I have a View with an UIImageView that I want to be 'selectable' so that the user can pick a new image.
The function for picking the new image is in the Controller.
Question
How do I call the myDatasourceController.handleTap() function by pressing the ImageView, so that the image picker is presented?
This is an example of my current setup
View
class myView: UICollectionViewCell {
lazy var profileImageView: UIImageView = {
let iv = UIImageView()
iv.isUserInteractionEnabled = true
iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(myDatasourceController.handleTap)))
return iv
}()
}
Controller
class myDatasourceController: UICollectionViewController,
UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
func handleTap(){
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// logic for picking the image
dismiss(animated: true, completion: nil)
}
}
This setup currently throws the error
unrecognized selector sent to instance 0x7f9163d493f0
which has led me to try various combinations of
handleTap(_:)
handleTap(sender: UITapGestureRecogniser)
/// etc
but I can't get any of them to work. How should I be constructing my View, Controller, and the interaction between them to present the image picker?
Use Like this
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(RegisterViewController. handleTap(gesture:)))
func handleTap(gesture: UIGestureRecognizer) {
// if the tapped view is a UIImageView then set it to imageview
if (gesture.view as? UIImageView) != nil {
print("Image Tapped")
picker.allowsEditing = false
picker.sourceType = .photoLibrary
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
present(picker, animated: true, completion: nil)
}
}
Use like this :
myDatasourceController.handleTap()
In your code :
iv.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(myDatasourceController.handleTap())))
The key to the solution is to implement a protocol / delegate, as suggested by #Akis
I've uploaded the full project to my github account. The key code is copied here.
View Controller
protocol ImagePickerDelegate: class {
func loadImagePicker()
}
class HomeViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ImagePickerDelegate {
let cellId = "cellId"
func loadImagePicker(){
print(" -- image picker -- ")
// load image picker
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// get the image
var selectedImageFromPicker: UIImage?
if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
selectedImageFromPicker = editedImage
}else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
selectedImageFromPicker = originalImage
}
if let selectedImage = selectedImageFromPicker {
//doSomethingWithTheImage(image: selectedImage)
}
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .black
collectionView?.register(HomeView.self, forCellWithReuseIdentifier: cellId)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! HomeView
cell.delegate = self
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height)
}
}
View
class HomeView: UICollectionViewCell {
// break retain cycle with weak var
weak var delegate: ImagePickerDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
lazy var profileImageView: UIImageView = {
let iv = UIImageView()
iv.isUserInteractionEnabled = true
iv.image = UIImage(named: "kuang-si-falls-waterfall-water-laos-50588.jpg")
iv.contentMode = .scaleAspectFill
let tap = UITapGestureRecognizer(target: self, action: #selector(loadImagePicker))
iv.addGestureRecognizer(tap)
return iv
}()
func loadImagePicker() {
delegate?.loadImagePicker()
print(" imagePickerProtocol called ")
}
func setupViews() {
backgroundColor = .white
addSubview(profileImageView)
profileImageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
profileImageView.frame = CGRect(x: 0, y: 0, width: 150, height: 150)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
I am using third party control for sidemenu named : MMDrawerController, and m handling UI using multiple storyboards.let me come to the point my sidemenu looks like this : Sidemenu Image
Trying to achieve :
1)When I click on the Parent, "main.storyboard" should be displayed.
2)When I click on the Management, "management.storyboard" should be displayed.
same sidemenu should be displayed across all storyboard file.
I have tried some code by my own but m not getting the sidemenu on "management.storyboard" :(
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch(indexPath.row)
{
case 4:
let mainstoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var welview = mainstoryboard.instantiateViewController(withIdentifier: "WelcomeParentViewController") as! WelcomeParentViewController
var welnav = UINavigationController(rootViewController: welview)
var appdel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
appdel.centerContainer!.centerViewController = welnav
appdel.centerContainer!.toggle(MMDrawerSide.left, animated: true, completion: nil)
break
case 5:
let mainstoryboard : UIStoryboard = UIStoryboard(name: "Management-Storyboard", bundle: nil)
var welview = mainstoryboard.instantiateViewController(withIdentifier: "ReportsViewController") as! ReportsViewController
var welnav = UINavigationController(rootViewController: welview)
var appdel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
appdel.centerContainer!.centerViewController = welnav
appdel.centerContainer!.toggle(MMDrawerSide.left, animated: true, completion: nil)
break
default :
break
}
I want same sidemenu across all storyboard file.
how to accomplish the above feature.Please Help.Thank you in advance.
MMDrawerController Code inside the appdelegate.swift
import UIKit
import GoogleMaps
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var centerContainer : MMDrawerController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if isUserLoggedIn()
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.gotoMainvc()
}
else
{
let rootViewController = self.window!.rootViewController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let setViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
rootViewController?.navigationController?.popToViewController(setViewController, animated: false)
}
return true
}
func isUserLoggedIn() -> Bool{
if let accessToken = UserDefaults.standard.object(forKey: "access_token") as? String
{
if (accessToken.characters.count) > 0{
return true
} else {
return false
}
}
else {
return false
}
}
func gotoMainvc()
{
var rootviewcontroller = self.window?.rootViewController
if(UIDevice.current.userInterfaceIdiom == .phone)
{
let mainstoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
var centerviewcontroller = mainstoryboard.instantiateViewController(withIdentifier: "WelcomeParentViewController") as! WelcomeParentViewController
var leftsideviewcontroller = mainstoryboard.instantiateViewController(withIdentifier: "LeftSideMenuViewController") as! LeftSideMenuViewController
let leftsidenav = UINavigationController(rootViewController: leftsideviewcontroller)
let centernav = UINavigationController(rootViewController: centerviewcontroller)
centerContainer = MMDrawerController(center: centernav, leftDrawerViewController: leftsidenav)
centerContainer?.openDrawerGestureModeMask = MMOpenDrawerGestureMode.panningCenterView
centerContainer?.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.panningCenterView
window?.rootViewController = centerContainer
window?.makeKeyAndVisible()
}
else{
let mainstoryboard2 : UIStoryboard = UIStoryboard(name: "Storyboard-iPad", bundle: nil)
var centerviewcontroller = mainstoryboard2.instantiateViewController(withIdentifier: "WelcomeParentViewController") as! WelcomeParentViewController
var leftsideviewcontroller = mainstoryboard2.instantiateViewController(withIdentifier: "LeftSideMenuViewController") as! LeftSideMenuViewController
let leftsidenav = UINavigationController(rootViewController: leftsideviewcontroller)
let centernav = UINavigationController(rootViewController: centerviewcontroller)
centerContainer = MMDrawerController(center: centernav, leftDrawerViewController: leftsidenav)
centerContainer?.openDrawerGestureModeMask = MMOpenDrawerGestureMode.panningCenterView
centerContainer?.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.panningCenterView
window?.rootViewController = centerContainer
window?.makeKeyAndVisible()
}
}
//MARK: sharedDelegate
func sharedDelegate() -> AppDelegate
{
return UIApplication.shared.delegate as! AppDelegate
}
}
Main View Controller
import UIKit
class ViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource , UIGestureRecognizerDelegate {
#IBOutlet weak var collectioncell: UICollectionView!
var objectProfile:SideMenuViewController!
var tapGesture = UITapGestureRecognizer()
override func viewDidLoad() {
super.viewDidLoad()
tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.myviewTapped(_:)))
tapGesture.numberOfTapsRequired = 1
tapGesture.numberOfTouchesRequired = 1
collectioncell.addGestureRecognizer(tapGesture)
collectioncell.isUserInteractionEnabled = true
let storyboard = UIStoryboard(name: "Main", bundle: nil)
self.objectProfile = storyboard.instantiateViewController(withIdentifier: "SideMenuViewController") as! SideMenuViewController
self.objectProfile.view.frame = CGRect(x: -(self.view.frame.size.width - 40), y: 0, width: self.view.frame.size.width - 40, height: self.view.frame.size.height)
self.view.addSubview(self.objectProfile.view)
self.navigationController?.didMove(toParentViewController: self.objectProfile)
self.collectioncell.layer.cornerRadius = 5.0
self.collectioncell.layer.borderWidth = 5.0
self.collectioncell.clipsToBounds = true
self.collectioncell.layer.borderColor = UIColor.clear.cgColor
self.collectioncell.layer.masksToBounds = true
}
func myviewTapped(_ sender: UITapGestureRecognizer) {
if self.objectProfile.view.isHidden == false {
UIView.animate(withDuration: 0.3)
{
self.objectProfile.view.frame = CGRect(x: -(self.view.frame.size.width - 90), y: 0, width: self.view.frame.size.width - 90, height: self.view.frame.size.height)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Mrnupressed(_ sender: UIBarButtonItem) {
UIView.animate(withDuration: 0.3)
{
self.objectProfile.view.frame = CGRect(x: 0 , y: 0, width: (self.view.frame.size.width - 100), height: self.view.frame.size.height)
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 6
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! MainCollectionViewCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let cellsize = CGSize(width: (collectioncell.bounds.size.width/2) - 12, height:(collectioncell.bounds.size.height/3) - 20)
return cellsize
}
}
Child View Controller
import UIKit
class SideMenuViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var sidemenutable: UITableView!
var stri:String!
var ArrarMenu:[String] = ["Home","SiteMep","Student","About Us","Help"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ArrarMenu.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SideMenuCell") as! SideMenuTableViewCell
let objarray = ArrarMenu[indexPath.row]
cell.lblitem.text = objarray
stri = objarray
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0{
self.performSegue(withIdentifier: "SegueForHome", sender: self)
}
}
}
In This Code I Am use Child View As Side Manu Controller
here is code open side from other storyboard
#IBAction func menutapped(_ sender: Any) {
var appdelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
appdelegate.centerContainer?.toggle(MMDrawerSide.left, animated: true, completion: nil)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("gallery count : \(self.arrayGallerySingle.count)")
return self.arrayGallerySingle.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gallerycell", for: indexPath) as! GalleryViewCell
return cell
}
//API Fetching method
func galleryFetch(){
let prs = [
"id": dealIDGallery,
"deal_single_page": "1" as String
]
Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion: { result in
let jsonResponseSingle = result as? NSDictionary
print(" jsonResponse\(String(describing: jsonResponseSingle))")
if let resultGallery = jsonResponseSingle?.value(forKey: "result") as? NSArray{
for keyValuesGallery in resultGallery {
let gallerySingle = (keyValuesGallery as AnyObject).value(forKey: "gallery_images") as? NSArray
print("Gallery Images Key: \(gallerySingle)")
self.arrayGallerySingle = gallerySingle as! [AnyObject]
DispatchQueue.main.async { () -> Void in
self.collectionView?.reloadData()
}
}
}
})
}
How will I show an array of images with key gallery_images on UICollectionViewCell?This line print("Gallery Images Key: \(gallerySingle)") prints the required array of images on console but I am unable to show on collectionView. My JSON response is http://www.jsoneditoronline.org/?id=8eccb63976d76be7d0b2d1b0e8f02306. I am using SDWebImage in my project also.I already checked datasource connection & collectionView IBoutlet as well as an image inside the cell. I am a beginner in Swift pls help and if required any further information pls ask
Swift 3.0 This is my updated Answer hope it will also help someone
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("gallery count : \(self.arrayGallerySingle.count)")
return self.arrayGallerySingle.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gallerycell", for: indexPath) as! GalleryViewCell
if let imgUrl = arrayGallerySingle[indexPath.row] as? String {
if let url = NSURL(string: imgUrl) {
cell.galleryImage?.sd_setImage(with: url as URL, placeholderImage: UIImage(named: "place holder image"), options: .lowPriority)
}
else{
let alertController = UIAlertController(title: "No Gallery Images", message: "test", preferredStyle: .alert)
let okButton = UIAlertAction(title: "Okay", style: .default, handler: nil)
alertController.addAction(okButton)
alertController.present(alertController, animated: true, completion: nil)
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: collectionView.frame.size.width/2, height: collectionView.frame.size.height/3)
}
func galleryFetch(){
let prs = [
"id": dealIDGallery,
"deal_single_page": "1" as String
]
Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion: { result in
let jsonResponseSingle = result as? NSDictionary
print(" jsonResponse\(String(describing: jsonResponseSingle))")
if let resultGallery = jsonResponseSingle?.value(forKey: "result") as? NSArray{
for keyValuesGallery in resultGallery {
let gallerySingle = (keyValuesGallery as AnyObject).value(forKey: "gallery_images") as? NSArray
print("Gallery Images Key: \(gallerySingle)")
self.arrayGallerySingle = gallerySingle as! [AnyObject]
if self.arrayGallerySingle.count > 0 {
DispatchQueue.main.async { () -> Void in
self.collectionView?.reloadData()
}
} else {
let alertController = UIAlertController(title: "Message", message: "No images found.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: self.doSomething))
self.present(alertController, animated: true, completion: nil)
}
}
}
})
}
Swift 3.0
you can implement this way with SDWebcache to load image in collectionView cell image.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gallerycell", for: indexPath) as! GalleryViewCell
if let imgUrl = arrayGallerySingle[indexPath.row] as? String {
if let url = URL(string: imgUrl) {
//Replace with your imageView outlet
cell.imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "place holder image"), options: .lowPriority)
}
}
return cell
}
And If you want to display 6 cell in collectionView Then you have to set UICollectionViewLayout method to defined size of cell as below.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: collectionView.frame.size.width/2, height: collectionView.frame.size.height/3)
}
You can display alert when array count is not empty and why you reload Collection view inside for loop, Implement it like below.
Service.StartWithoutLoading(prs as [String : AnyObject]?, onCompletion: { result in
let jsonResponseSingle = result as? NSDictionary
print(" jsonResponse\(String(describing: jsonResponseSingle))")
if let resultGallery = jsonResponseSingle?.value(forKey: "result") as? NSArray{
for keyValuesGallery in resultGallery {
let gallerySingle = (keyValuesGallery as AnyObject).value(forKey: "gallery_images") as? NSArray
print("Gallery Images Key: \(gallerySingle)")
self.arrayGallerySingle = gallerySingle as! [AnyObject]
}
if self.arrayGallerySingle.count > 0 {
DispatchQueue.main.async { () -> Void in
self.collectionView?.reloadData()
}
} else {
let alertController = UIAlertController(title: "Your Title", message: "their is no images", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alertController, animated: tru, completion: nil)
}
}
})
I know that this question has answered in this site But I tried the code and receive an Error please help me to show my camera roll in a collection view (I know that I have to add photo usage in info.plist please Just focus on my codes thanks!!!)
here is my view controller code
class translateViewController: UIViewController , UINavigationControllerDelegate , UIImagePickerControllerDelegate , UICollectionViewDataSource, UICollectionViewDelegate {
#IBOutlet var myimageView: UIImageView!
#IBAction func importImage(_ sender: Any) {
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.photoLibrary
image.allowsEditing = false
self.present(image , animated: true)
{
}
}
#IBOutlet weak var cameraRollCollectionView: UICollectionView!
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
myimageView.image = image
}
else {
print("Error")
}
self.dismiss(animated: true, completion: nil)
}
#IBOutlet var translatebackgroundimg: UIImageView!
#IBOutlet var translatefrontimg: UIImageView!
var assetCollection: PHAssetCollection!
var photosAsset: PHFetchResult<AnyObject>!
var assetThumbnailSize: CGSize!
override func viewDidLoad() {
super.viewDidLoad()
let fetchOptions = PHFetchOptions()
let collection:PHFetchResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
if let first_Obj:AnyObject = collection.firstObject{
//found the album
self.assetCollection = first_Obj as! PHAssetCollection
}
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = CGRect(x: self.translatebackgroundimg.frame.origin.x, y: self.translatebackgroundimg.frame.origin.y, width: self.translatebackgroundimg.frame.size.width, height: self.translatebackgroundimg.frame.size.height)
blurView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.translatebackgroundimg.addSubview(blurView)
// Do any additional setup after loading the view.
translatefrontimg.image = UIImage(named: "Translate.png")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = translatebackgroundimg.bounds
translatebackgroundimg.addSubview(blurView)
translatebackgroundimg.frame = self.view.bounds
}
override func viewWillAppear(_ animated: Bool) {
// Get size of the collectionView cell for thumbnail image
if let layout = self.cameraRollCollectionView!.collectionViewLayout as? UICollectionViewFlowLayout{
let cellSize = layout.itemSize
self.assetThumbnailSize = CGSize(width: cellSize.width, height: cellSize.height)
}
//fetch the photos from collection
self.photosAsset = (PHAsset.fetchAssets(in: self.assetCollection, options: nil) as AnyObject!) as! PHFetchResult<AnyObject>!
self.cameraRollCollectionView!.reloadData()
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
var count: Int = 0
if(self.photosAsset != nil){
count = self.photosAsset.count
}
return count;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cameraCell", for: indexPath as IndexPath)
//Modify the cell
let asset: PHAsset = self.photosAsset[indexPath.item] as! PHAsset
PHImageManager.default().requestImage(for: asset, targetSize: self.assetThumbnailSize, contentMode: .aspectFill, options: nil, resultHandler: {(result, info)in
if result != nil {
cameraCell.userImage.image = result
}
})
return cell
}
// MARK: - UICollectionViewDelegateFlowLayout methods
func collectionView(collectinView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 4
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1
}
// UIImagePickerControllerDelegate Methods
func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
picker.dismiss(animated: true, completion: nil)
}
and here is my CollectionViewCell codes
class cameraCell: UICollectionViewCell , UIImagePickerControllerDelegate {
#IBOutlet weak var userImage: UIImageView!
func configurecell(image: UIImage){
userImage.image = image
}
}
i am working on swift 3.0.1 and xcode 8.2.1,
i want to select multiple images from gallery and show it in different collage in collectionView, when i select images from gallery and press done button collection view did not show anything but when i press Mobile Screen then images shown on the screen. tell me whats wrong in my code and how to get my task. I import these frameworks Photos, BSImagePicker, BSGridCollectionViewLayout. here is my code
#IBOutlet weak var collection: UICollectionView!
var imagePicker = UIImagePickerController()
var imageArray = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
imagePicker.delegate = self
collection.delegate = self
collection.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Camera(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(.camera){
imagePicker.sourceType = .camera
imagePicker.allowsEditing = false
imagePicker.cameraCaptureMode = .photo
imagePicker.cameraFlashMode = .auto
imagePicker.modalPresentationStyle = .fullScreen
self.present(imagePicker, animated: true, completion: nil)
}
else{
let alert = UIAlertController(title: "No Camera", message: "Your Device has No Camera", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .destructive, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
#IBAction func Library(_ sender: Any) {
let vc = BSImagePickerViewController()
vc.maxNumberOfSelections = 4
//vc.takePhotoIcon = UIImage(named: "Tick")
vc.albumButton.tintColor = UIColor.blue
vc.cancelButton.tintColor = UIColor.blue
vc.doneButton.tintColor = UIColor.blue
vc.selectionCharacter = "✓"
vc.selectionFillColor = UIColor.green
vc.selectionStrokeColor = UIColor.clear
vc.selectionShadowColor = UIColor.black
vc.selectionTextAttributes[NSForegroundColorAttributeName] = UIColor.lightGray
vc.cellsPerRow = {( verticalSize: UIUserInterfaceSizeClass, horizontalSize: UIUserInterfaceSizeClass) -> Int in
switch (verticalSize, horizontalSize){
case(.compact , .regular):
return 3
case (.compact, .compact): // iPhone5-6 landscape
return 3
case (.regular, .regular): // iPad portrait/landscape
return 3
default:
return 3
}
}
bs_presentImagePickerController(vc, animated: true, select: { (asset: PHAsset) -> Void in
print("Selected: \(asset)")
let imageManager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.isSynchronous = true
requestOptions.deliveryMode = .highQualityFormat
imageManager.requestImage(for: asset, targetSize: CGSize(width: 132, height: 114) ,contentMode: .aspectFill, options: requestOptions, resultHandler:
{
image, error in
self.imageArray.append(image!)
})
self.collection.reloadData()
},
deselect: { (asset: PHAsset) -> Void in
print("Deselected: \(asset)")
},
cancel: { (asset: [PHAsset]) -> Void in
print("Cancel: \(asset)")
},
finish: { (asset: [PHAsset]) -> Void in
print("Finish: \(asset)")
}, completion: nil)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imageArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let Cell : CellClass = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CellClass
Cell.imageView.image = self.imageArray[indexPath.row]
return Cell
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
imageArray.append(pickedImage)
}
else {
print("Image not Picked")
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.imagePicker = UIImagePickerController()
dismiss(animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width / 3 - 1
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 1.0
}
func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.red
}
func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.green
}