show viewController from collectionView without storyboards - swift

I am having some trouble showing a viewController programmatically (without storyboards) from a collectionView. I would think this is pretty easy but I am having some difficulty figuring this out as I am somewhat new to swift. I believe collectionViewCells are not delegates by default, so I have tried implementing the didSelectItemAt in the collectionView class but still no luck. On tap of the cell I am receiving a print statement, just not having any show segue. See collectionViewCell code below, and thanks in advance!
// collectionViewCell class
class PlanningCell: BaseCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
cv.dataSource = self
cv.delegate = self
return cv
}()
//collectionViewCell variables
var plannedPlaces = [CurrentPlanner]()
let cellId = "cellId"
var basePlanningCell: BasePlanningCell!
override func setupViews() {
super.setupViews()
addSubview(collectionView)
collectionView.register(BasePlanningCell.self, forCellWithReuseIdentifier: cellId)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return plannedPlaces.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! BasePlanningCell
cell.currentPlanner = plannedPlaces[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("did tap")
let plannersDetailVC = PlanningPlaceDetailsVC()
plannersDetailVC.navigationTitle = plannedPlaces[(indexPath.row)].planningPlace
// below I am receiving the use of unresolved identifier "show" error
show(plannersDetailVC, sender: self)
}
}

Normally, when you want to present another view controoler, you need to call this function
self.present(yourViewController, animated: true, completion: nil)
However, you cannot do that in the place you do the print because the function present is only available in view controllers. So now the problem becomes, how to direct your cell click to the parent view controller and pass a string. You have two options, you can either create a delegate like this, or do a NSNotificationCenter post call, the second one being easier.
When you pass the cell click event to your parent view controller, you can start calling that method mention above to navigate to another view controoler

let vc = UIStoryboard(name:"Main", bundle:nil).instantiateViewController(withIdentifier: "VCIdentifier") as! PlanningPlaceDetailsVC
present(vc, animated: true, completion: nil)
Don't forget to set the PlanningPlaceDetailsVC Identifier
Updated for a VC setted by code:
let vc : UIViewController = PlanningPlaceDetailsVC()
self.presentViewController(vc, animated: true, completion: nil)

Related

Updating height constraint of UICollectionView not working

I have this collection view inside my collection view cell, of which I will populate with more cells. I'm currently trying to update the height of the UICollectionView upon any editing events to the inner cells text field.
This currently works when I load the page, click into the field and then scroll. However, if I load the page, scroll first and then click into the field, it doesn't work but I'm unsure why. I can't see anything that is running differently.
Any help would be appreciated. Thanks.
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
var heightAnchor: NSLayoutConstraint?
var collectionView: UICollectionView!
static let reuseIdentifier: String = "MyCollectionViewCell"
override func awakeFromNib() {
super.awakeFromNib()
var layout: UICollectionViewLayout = UICollectionViewLayout()
collectionView = UICollectionView(frame: contentView, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.isScrollEnabled = false
self.contentView.addSubview(collectionView)
heightAnchor = collectionView.heightAnchor.constraint(equalToConstant: 600)
heightAnchor?.isActive = true
collectionView.anchorViewPosition(parent: self.contentView, leading: .zero, top: .zero, bottom: .zero)
collectionView.register(UINib(nibName: "MyInnerCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: MyInnerCollectionViewCell.reuseIdentifier)
}
override func layoutSubviews() {
super.layoutSubviews()
collectionview.widthAnchor.constraint(equalToConstant: 288).isActive = true
}
#objc func updateCollectionViewSize() {
heightAnchor?.constant = 200
}
}
extension MyCollectionViewCell: UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyInnerCollectionViewCell", for: indexPath) as? MyInnerCollectionViewCell
cell?.field.addTarget(self, action: #selector(updateCollectionViewSize()), for: .allEditingEvents)
return cell!
}
}

Hero ViewController animation with collectionView - swift

I'm trying to present a view controller whenever I tap on a collection view cellwith the zoom effect.
As far as I know Hero framework works using HeroID's, you set the same id in the fromView and in the toView and the frameworks does the hard work for you.
I have set It up this way:
in viewcontroller1 :
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! CollectionViewCell
cell.heroID = "profheroid"
let viewcontroller2 = ViewController2()
viewcontroller2.configureController(with: arrayOfModels[indexPath.item])
viewcontroller2.heroModalAnimationType = .zoom
viewcontroller2.modalPresentationStyle = .fullScreen
self.navigationController?.present(viewcontroller2, animated: true, completion: nil)
}
and in viewcontroller2:
override func viewDidLoad() {
super.viewDidLoad()
view.heroID = "profheroid"
}
The problem happens whenever I tap on a collectionviewCell the presentation happens correctly but I see so many cells being presented at the same time.
I think this happens because cell.heroID = "profheroid" is applied to more cells at the same time.
How can I make sure that when the cell is presented the heroID's are only in the cell tapped and in the viewcontroller's view??
I think you must clear this heroID when cell is reused and after VC is presented.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
cell.heroID = nil // or empty
}
I think you must reset heroID to nil in cellForItemAt:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YourCollectionViewCell.description(), for: indexPath) as? YourCollectionViewCell else {
return UICollectionViewCell()
}
cell.heroID = nil
return cell
}
Reset all visible cell's heroID to nil, and only set heroID for cell selected with value before present:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.visibleCells.forEach { cell in
cell.heroID = nil //reset heroID
}
guard let cell = collectionView.cellForItem(at: indexPath) else { return }
cell.heroID = "profheroid"
let viewcontroller2 = ViewController2()
viewcontroller2.configureController(with: arrayOfModels[indexPath.item])
viewcontroller2.heroModalAnimationType = .zoom
viewcontroller2.modalPresentationStyle = .fullScreen
self.navigationController?.present(viewcontroller2, animated: true, completion: nil)
}

Segue from selected collection view cell sends to wrong collection view

I am using swift. I'm trying to create a collectionView segue to lead to a new viewController.
I have a series of (lets say 8) different images and labels as an array within the collectionView, and the when selected, I want the user to be sent to another view controller (with 8 different possibilities - one for each cell). I have been able to get the app to build, but the behaviour from selecting a cell is wrong.
The first cell that is selected has no response, then the next cell initiates a segue - but to the previously selected one! Each time a different cell is selected, it segues to the previous selected cell. Can anyone help me correct this error?
I have used performSegue and pushViewController separately, following different tutorials on youtube, but each resolves to the same issue.
The various view controllers to segue to have been allocated their own storyboardID in the main.storyboard file. The initial view controller is embedded within a navigation controller, and each new veiwcontroller (to segue to) has been connected to the collection view of the main view controller.
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet var CollectionView: UICollectionView!
// created an array for labels
let NamesForSectionTitles = ["Overview","Canopy trees","Mid-story trees","Understory plants","Birds","Mammals","Ferns","Butterflys"]
// created list of images to be loaded in the collectionview
let sectionIconImages: [UIImage] = [
UIImage(named: "IMG_8750_landscape_night")!,
UIImage(named: "IMG_8789_Trees")!,
UIImage(named: "IMG_2185_Tree_Olearia")!,
UIImage(named: "_MG_9528_Herb_Flower")!,
UIImage(named: "IMG_3654-")!,
UIImage(named: "IMG_9892-2")!,
UIImage(named: "IMG_9496_Ferns_crozier")!,
UIImage(named: "IMG_7707_Butterfly")!,
]
override func viewDidLoad() {
super.viewDidLoad()
// load the data sources and delegate
CollectionView.dataSource = self
CollectionView.delegate = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return NamesForSectionTitles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) ->
UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.SectionTitle.text = NamesForSectionTitles[indexPath.row]
cell.sectionImages.image = sectionIconImages[indexPath.row]
return cell
}
// tells the collection view that upon selecting a cell, show the next UIView controller, as suggested in storyboard name (main.storyboard property) - tutoral from https://www.youtube.com/watch?v=pwZCksvXGRw&list=PLPUDRZDcNNsMdyfZVw4CJDT1Wu8cYx_6E&index=7&t=0s
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: NamesForSectionTitles[indexPath.row], sender: self)
}
}
The viewer should see an image view with a label, that when selected takes them to a new collection view.
Can't Comment so posting an answer
I think
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) is causing the issue.
Please try changing that line to:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)

Programmatically made UICollectionViewController not showing cells

The background is black and the cells are white though none of the cells are showing in the simulator? would any one know why this might be?
import UIKit
import Foundation
class ChatLog: UICollectionViewController, UITextFieldDelegate, UICollectionViewDelegateFlowLayout {
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = UIColor.black
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
cell.backgroundColor = UIColor.white
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.height, height: 80)
}
}
Update:
Initialising the ChatLog view controller programmatically as follows means that the UICollectionView datasource methods aren't called e.g collectionView(_:cellForItemAt:) isn't called.
let newViewController = ChatLog(collectionViewLayout: UICollectionViewLayout())
Replace with this:
let newViewController = ChatLog(collectionViewLayout: UICollectionViewFlowLayout())
--
As you have declared a UICollectionViewController, you don't actually need to set explicitly in code, the delegate and dataSource properties of your collection view.
Simply make sure that in the Main.storyboard, you have set the class of your UICollectionViewController to ChatLog by clicking on the view controller and then the identity inspector. Also ensure that you have clicked the UICollectionViewCell and set it's Identifier to "cellId".
If this is a multiple view controller project, ensure that it is possible to navigate to ChatLog view controller by making it initial view controller or providing segue/navigation to this view controller from another view controller.
Pictures below outline my solution.
Set the delegate and datasource of the collectionView. The datasource and delegate methods(numberOfItemsInSection, cellForItemAtIndexpath, etc) will be called only if you have set the delegate and datasource. You can set it either in code or in storyboard(if you have used storyboard to design the collectionView)
In the viewDidLoad you can add
collectionView.delegate = self
collectionView.datasource = self

How to select multiple images from UICollectionView and transfer them to another View Controller?

The code is written in Swift. I'm building a social app where the user can make posts. I'm using Firebase as a backend (database, storage). So, I have a UICollectionView that gets all the photos from the photo library of the device and populate the collection view using a custom cell. In the same View controller, I have another custom cell that the user can use to take a photo and use it to make a post. To make it clearer:
If the user decides to take a photo, when they click on "Use photo" they need to be presented to a new view controller that should display the photo they just took along with other options (such as title, description and tags using UITextFields & UITextView).
If the user decides to select multiple photos from their own library, I have to somehow mark those photos/cells (i.e. using a button for a checkmark), add the selected photos to an array (with some limit, maybe 10 photos top). When they click "Next" button, the array needs to be sent to the New Post View Controller where all the images should be dynamically displayed maybe using a horizontal UICollectionView (?!) (with an option to remove an image if it was selected by accident) and again, as above, have the opportunity to add title, description, etc. Now, I cannot figure out how to do any of that.
I looked for a solution, but I'm kind of stuck on this for couple days now, so help is very much welcome!
Here's what I have in the Collection View controller (PS: I didn't include the part with the function that gets the images from the Photos)
import UIKit
import Photos
class PrePhotoPostVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UICollectionViewDelegateFlowLayout {
#IBOutlet weak var nextButton: UIBarButtonItem!
var photosLibraryArray = [UIImage]()
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
checkPhotoLibraryPermission()
setupCollectionViewDelegates()
}
#IBAction func cancelButtonPressed (_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
#IBAction func nextButtonPressed (_ sender: UIBarButtonItem) {
nextButton.isEnabled = false
}
#IBAction func takeAphotoButtonPressed (_ sender: UIButton) {
// Camera Autorization
AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { response in
if response {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
else {
print("Camera isn't available in similator")
}
}
else {
print("unautorized")
}
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if section == 0 {
return 1
} else {
return photosLibraryArray.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 0 {
let cellCamera = collectionView.dequeueReusableCell(withReuseIdentifier: cellPrePostCameraCell, for: indexPath)
return cellCamera
}
else {
let cellPhotoLibrary = collectionView.dequeueReusableCell(withReuseIdentifier: cellPrePostPhotoLibrary, for: indexPath) as! PrePhotoPostPhotoLIbraryCell
cellPhotoLibrary.awakeFromNib()
cellPhotoLibrary.photoLibraryImage.image = photosLibraryArray[indexPath.row]
return cellPhotoLibrary
}
}
}
A screenshot of what this UICollectionView looks like:
Here's my code from the Photo Library Cell:
import UIKit
class PrePhotoPostPhotoLIbraryCell: UICollectionViewCell {
// MARK: Outlets
#IBOutlet weak var photoLibraryImage: UIImageView!
// var selectedPhotos = [UIImageView]()
#IBAction func selectedButtonPressed(_ sender: UIButton) {
self.layer.borderWidth = 3.0
self.layer.borderColor = isSelected ? UIColor.blue.cgColor : UIColor.clear.cgColor
}
override func awakeFromNib() {
photoLibraryImage.clipsToBounds = true
photoLibraryImage.contentMode = .scaleAspectFill
photoLibraryImage.layer.borderColor = UIColor.clear.cgColor
photoLibraryImage.layer.borderWidth = 1
photoLibraryImage.layer.cornerRadius = 5
}
}
First of all declare an array of mutable type that will store the selected cells item in it.
var _selectedCells : NSMutableArray = []
then in your viewDidLoad function add below code.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//this will allow multiple selection on uicollectionviewcell
CollectionView.allowsMultipleSelection=true //CollectionView is your CollectionView outlet
}
Then, Implement delegate functions of collectionview for selecting and deselecting cells
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
//add the selected cell contents to _selectedCells arr when cell is selected
_selectedCells.add(indexPath)
collectionView.reloadItems(at: [indexPath])
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
//remove the selected cell contents from _selectedCells arr when cell is De-Selected
_selectedCells.remove(indexPath)
collectionView.reloadItems(at: [indexPath])
}
I'd suggest saving the NSIndexPath of the selected item in an array, and then using that for the basis of comparison in the delegate function cellForItemAt indexPath.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YOUR_CELL_Identifier", for: indexPath as IndexPath)
//add your tick mark image to the cell in your storyboard or xib file.
let tickImage = cell.viewWithTag(YOUR_IMAGE_TAG_HERE) as? UIImageView
//Show tickImage if the cell is selected and hide tickImage if cell is NotSelected/deSelected.or whatever action you want to perform in case of selection and deselection of cell.
if _selectedCells.contains(indexPath) {
cell.isSelected=true
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: UICollectionViewScrollPosition.top)
tickImage?.isHidden=false
}
else{
cell.isSelected=false
tickImage?.isHidden=true
}
return cell
}
In Order to send items to next controller, get all the items from selected indexpaths.