Print image name to console from UICollectionView - swift

I'm working with a UICollectionView where I have a UIImage with a Tap Gesture Recogniser as the cell model for my CollectionView. I also have 57 images with different names that I want to print to the console depending on which image I tap on.
Here is my code:
import UIKit
class ViewController: UIViewController {
let OLLData = OLLCases()
// MARK: - Outlets
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// MARK: - Navigation
#IBAction func isSelected(_ sender: Any) {
print("selected \(caseName)")
}
}
//MARK: - Data source
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return OLLData.list.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
let image = OLLData.list[indexPath.item].image
let caseName = OLLData.list[indexPath.item].image
cell.label.text = caseName
cell.imageView.image = UIImage(named: image)
return cell
}
}
I then have another swift file (PhotoCell )where I have the IBOutlets for label and imageView.
What methods are there of doing this?
Thanks.

You can use UICollectionViewDelegate method to detect tap on cell but to use that first of all your UICollectionView need to confirm the delegate with your UIViewController like:
collectionView.delegate = self
in your viewDidLoad method.
then you need to replace
extension ViewController: UICollectionViewDataSource {
with
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
and use delegate method
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
and you can get selected image name with
let caseName = OLLData.list[indexPath.item].image
print(caseName)
and didSelectItemAt will look like:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let caseName = OLLData.list[indexPath.item].image
print(caseName)
}
EDIT:
Your extension will look like:
extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return OLLData.list.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as! PhotoCell
let image = OLLData.list[indexPath.item].image
let caseName = OLLData.list[indexPath.item].image
cell.label.text = caseName
cell.imageView.image = UIImage(named: image)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let caseName = OLLData.list[indexPath.item].image
print(caseName)
}
}

You should implement didSelectItemAt method, then get the cell you've selected like this:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! PhotoCell
print(cell.imageView)
print(cell.label)
}
Hope this help

Add an extension for UICollectionViewDelegate below the last extension in your ViewController:
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(OLLData.list[indexPath.item].image)
}
}

Related

my xcode version is 13 and not support the collectionView below method

import UIKit
class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
var shoppingapp:[String] = ["cher","sale Small","shoes"]
override func viewDidLoad() {
super.viewDidLoad()
}
//this function is not working in my xcode 13 not calle this function
# func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
# return shoppingapp.count
# }
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionCell
cell.shoppinfappimage.image = UIImage(named: shoppingapp[indexPath.row] + ".jpeg")
cell.shoppinfappimage.layer.cornerRadius=50.0
return cell
}
}
I don't know which other method is there I am learning and practical in iOS application development****
First, please remove # from the code. Divide him into the ViewController extension.
extension ViewController: UICollectionViewDelegate,UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return shoppingapp.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionCell
cell.shoppinfappimage.image = UIImage(named: shoppingapp[indexPath.row] + ".jpeg")
cell.shoppinfappimage.layer.cornerRadius=50.0
return cell
}
}
But when I saw your code, I think you didn't declare delegate and DataSource.
//in viewDidLoad
collectionView.delegate = self
collectionView.dataSource = self
Write the code above in viewDidLoad. So I couldn't do a lot either.
If it didn't work, try it like this.
#available(iOS 13.0, *)
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return shoppingapp.count
}
I hope the writing helps me.

Collection view inside a collection view

As of title, I'm having trouble with the issue of nesting collectionViews. I found a workaround gimmicky solution but I'm not really satisfied with the result:
class ViewController3: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var outCollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
outCollection.dataSource = self
outCollection.delegate = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath:
IndexPath) -> UICollectionViewCell {
let cell = outCollection.dequeueReusableCell(withReuseIdentifier: "outCell", for:
indexPath) as! CollectionViewCell
cell.backgroundColor = .green
cell.setViewDD() // gimmick HERE
return cell
}
}
and for the CollectionViewCell
class CollectionViewCell: UICollectionViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var inCollection: UICollectionView!
func setViewDD() {
self.inCollection.delegate = self
self.inCollection.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = inCollection.dequeueReusableCell(withReuseIdentifier: "inCell", for: indexPath) as! innercellulosa
cell.backgroundColor = .red
return cell
}
}
if I try to set the delegate and datasource of the innerCollection (either in VC3 or CVCell) I stumble in multiple problems which I can't solve.

UICollectionViewLayout Not working with UIImage in Swift 5 and Xcode 11

Please check this attached code and screen short. It's work fine when I set the color of container view but when I add UIImage in cell then it's not working. I changed the imageview content mode but it's not working.
class ViewController: UIViewController {
#IBOutlet weak var segColumn: UISegmentedControl!
#IBOutlet weak var collectionView: UICollectionView!
fileprivate var items: [UIImage] = [ // My images ]
override func viewDidLoad() {
super.viewDidLoad()
self.setup()
}
}
extension ViewController: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.imgCell.image = items[indexPath.row]
cell.imgCell.contentMode = .scaleAspectFill
cell.contentView.backgroundColor = .red
return cell
}
}
extension ViewController: UICollectionViewDelegateFlowLayout{
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: (collectionView.bounds.width/3 - 2), height: (collectionView.bounds.width/3))
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 2
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 2
}
}
Please try this solution. I think there are some changes from Xcode 11.
Change the CollectionView Estimate Size to None then it will work.
it is probably because the red is dominating over the image
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.imgCell.image = items[indexPath.row]
cell.imgCell.contentMode = .scaleAspectFill
cell.contentView.backgroundColor = .red
return cell
}
try:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.contentView.backgroundColor = .red
cell.imgCell.image = items[indexPath.row]
cell.imgCell.contentMode = .scaleAspectFill
return cell
}

UIcollectionView Cell set ZIndex . I want to create Card Cell using UICollectionView

Swift
I am trying to create card style cell. So i am using collection view and set minimumLineSpacingForSectionAt in negative this code is working it looks good.
Problem is when I have a scroller bottom to top then first cell is a top side but I don't have a need on top here i have attached my code please check. I have Attached Error Image after scrolling issue
class SecondViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
let kItemSpace: CGFloat = -60.0
#IBOutlet weak var collection_setting: UICollectionView!
#IBOutlet var btn_top: UIButton!
var ary: NSMutableArray = NSMutableArray()
var ary_show: NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
ary = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//-----------------------------------------------------------------------------------
// MARK: - collection DataSource & Delegate
//-----------------------------------------------------------------------------------
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.ary.count
}
// make a cell for each cell index path
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "smallCollectionViewCell", for: indexPath as IndexPath) as! smallCollectionViewCell
cell.inner_view.dropShadow()
cell.inner_view.backgroundColor = .random()
cell.layer.zPosition = -1
cell.lbl_.text = "DEMO - \(indexPath.row)"
//cell.bringSubview(toFront: collectionView)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.frame.size.width, height: 100 )
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: NSInteger) -> CGFloat {
return kItemSpace
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
print(indexPath.row)
if(indexPath.row == 14)
{
print("--------------->",indexPath.row)
cell.layer.zPosition = 0
}else
{
cell.layer.zPosition = -1
}
}
}
Demo - 7 ,Demo - 8 , Demo - 9 is looking good but others are not showing as I want . first time this is looking correctly. this problem has come after scrolling.
Try this code please.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "smallCollectionViewCell", for: indexPath as IndexPath) as! smallCollectionViewCell
if cell == nil {
cell.inner_view.dropShadow()
cell.inner_view.backgroundColor = .random()
}
cell.layer.zPosition = -1
cell.lbl_.text = "DEMO - \(indexPath.row)"
return cell
}
cell.layer.zPosition = CGFloat(array.count - indexPath.row)

pass data from UITableViewCell to UIViewController

I have UITableViewCell and I want to send the indexPath.row number to UIViewController using didSet, but xcode gives me an error when i use the value for other things (in UIViewController) says that the value is nil error: unexpectedly found null when unwrapping an optional value.
But if I print in the variable in UIViewController the value appears.
What i do? Thanks.
class TableViewCellCentral: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var CollectionData: UICollectionView!
var send = Int() {
didSet{
ViewController().reload = send
}
}
override func awakeFromNib() {
super.awakeFromNib()
CollectionData.dataSource = self
CollectionData.delegate = self
CollectionData.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = CollectionData.dequeueReusableCell(withReuseIdentifier: "CellData", for: indexPath) as! CollectionViewCellData
cell.LabelData.text! = "number \(indexPath.row)"
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = CollectionData.dequeueReusableCell(withReuseIdentifier: "CellData", for: indexPath) as! CollectionViewCellData
send = indexPath.row
CollectionData.reloadData()
}
}
ViewController() is just an instance of your ViewController. What you're doing when you say ViewController() is you're creating a new ViewController, rather than accessing the one you're looking for. If you want the indexPath.row, you need to send it to the actual VC, not just an instance of it.
You need to keep in mind that not all data is loaded instantly and at the same time, also that it does not always load in the order that you expect it to. It is possible that you are asking for the data before it is even assigned. Try
import UIKit
class TableViewCellCentral: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var CollectionData: UICollectionView!
var send = Int() {
didSet {
ViewController().reload = send
}
}
override func awakeFromNib() {
super.awakeFromNib()
CollectionData.dataSource = self
CollectionData.delegate = self
CollectionData.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = CollectionData.dequeueReusableCell(withReuseIdentifier: "CellData", for: indexPath) as! CollectionViewCellData
if indexPath.row != nil {
cell.LabelData.text! = "number \(self.indexPath.row)"
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = CollectionData.dequeueReusableCell(withReuseIdentifier: "CellData", for: indexPath) as! CollectionViewCellData
send = indexPath.row
CollectionData.reloadData()
}
}
I am only printing if the value is not nil! Let me know if you have more questions, or let us know if my solution is not working. =)