I have a collectionView and I am using a custom cell that shows an Image and label. I am populating the view with an array. When a cell is selected, I want a new activity to open and the name of the class to be passed through.
Here is my code:
class CollectionViewController: UICollectionViewController {
let classes = ["English","Math","Science","Social Studies","Other","Technology"]
let class_images : [UIImage] = [
UIImage(named: "English")!,
UIImage(named: "Math")!,
UIImage(named: "Science")!,
UIImage(named: "Social Studies")!,
UIImage(named: "Other")!,
UIImage(named: "Technology")!
]
override func viewDidLoad() {
super.viewDidLoad()
var layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsets(top: 22, left: 22, bottom: 22, right: 22)
layout.minimumInteritemSpacing = 22
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return classes.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "class_cell", for: indexPath) as! custom_class_cell
cell.class_name.text = classes[indexPath.item]
cell.class_image.image = class_images[indexPath.item]
// Configure the cell
cell.layer.borderWidth = 1.0
cell.layer.borderColor = UIColor.black.cgColor
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//This isn't the right code, but an example of what I want to do!
if (indexPath=1){
let vc = self.storyboard?.instantiateViewController(withIdentifier:
"classes")
self.present(vc!, animated: true, completion: nil)
//I want to pass this string to the class
let class_name2 = "English"
}
else if(indexPath=2){
let vc = self.storyboard?.instantiateViewController(withIdentifier:
"classes")
self.present(vc!, animated: true, completion: nil)
//I want to pass this string to the class
let class_name2 = "Math"
//it keeps going through the technology cell
}
}
In the didSelectItemAt method, there is an example of what I am trying to do, but the code isn't right. I want to do this for all cells English to Technology. Thank you in advance and let me know if you have any questions!
easiest way:
in dest controller (let's say is a DetailController instance)
you should have:
class DetailController...
... var myInfo : MyInfo?
(MyInfo should contain ALL data You want to pass.)
and in prepare for segue:
vc.myInfo = Info(class_name2)
in viewDidLoad populate your UI:
override func viewDidLoad() {
super.viewDidLoad()
self.detail.text = self. myInfo....
It is actually a really simple solution, I just over complicated it!
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let valueToPass = classes[indexPath.row]
That gets you name of each class when the cell is clicked. After that, just do the prepare for segue method.
Related
So I create a UICollectionViewController class along with a custom UICollectionViewCell. I am presenting a new UIViewController from the CollectionView and then dismissing it in the UIViewController in order to return to the CollectionView. Everything works except for the fact that after dismissing the UIViewController it still remains in memory which is not what I want. I would like to completely destroy the UIViewController once it is dismiss but cannot figure out how do it.
Am I doing anything wrong? Is it normal for the dismiss ViewController to remain in memory after it's dismissal?
// UICollectionViewController class
class MyCollection: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellId = "cellId"
override func viewDidLoad() {
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: cellId)
}
let viewControllers:[UIViewController] = [ViewController1()]
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewControllers.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let activityCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CustomCell
return activityCell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = viewControllers[indexPath.item]
present(vc, animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 90)
}
}
// Custom UICollectionViewCell class
class CustomCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .red
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ViewController1: UIViewController {
lazy var dismissButton: UIButton = {
let newButton = UIButton(type: .system)
newButton.setTitle("Dismiss", for: .normal)
newButton.backgroundColor = .red
newButton.addTarget(self, action: #selector(dismissView), for: .touchUpInside)
newButton.translatesAutoresizingMaskIntoConstraints = false
return newButton
}()
#objc func dismissView() {
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(dismissButton)
NSLayoutConstraint.activate([
dissmissButton.centerXAnchor.constraint(equalTo: view.centerXAnchor)
dissmissButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
])
}
}
Reason why ViewController1 instance is not destroyed completely?
Even after the viewController is dismissed, you're still holding the reference to it inside MyCollection's viewControllers array.
Solution:
In case, you want a brand new instance of the controller everytime a cell is tapped, there is no need to store the controller in viewControllers array.
Simply update didSelectItemAt method to,
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = ViewController1() //here......
present(vc, animated: true, completion: nil)
}
No you are not doing it wrong. There is no strong retain cycle within your code.
The only problem is, even after you dismiss your view controller, it still resides in here
let viewControllers:[UIViewController] = [ViewController1()]
If you want the instance to be destroyed completely you need to remove it from the array as well.
It's not a good choice to make a global variable of a viewController.Once you still hold it,you'll be unable to destroy it.Do it like this:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc:UIViewController?
switch indexPath.row {
case 0:
vc = ViewController1()
case 1:
vc = ViewController2()
default:
vc = ViewController0()
}
present(vc!, animated: true, completion: nil)
}
And if there are many viewControllers, maybe it will be better to create a Array of Class like this:
guard let nameSpace = Bundle.main.infoDictionary?["CFBundleName"] as? String else { return }
let clsName = String(format: "%#.%#", nameSpace, cList[indexPath.row])
let cls = (NSClassFromString(clsName) as? UIViewController.Type)!
let vc = cls.init()
present(vc, animated: true, completion: nil)
clist:let cList = ["FirstController","SecondController"]
PS:
Of course I would not use this route if I get 50 ViewControllers.I just think that we can just use the most convenient way to solve the problem.
Hope this will help you.
I want to show cells in collection view like in circular list, means that after the last cell of the collection view, on scrolling the collection view shows the first cell again, like circular linklist
I have tried using icrousel, but as icarosuel deals with views only, I don't want to finish the collection view completely and start again with icarousel, so is there any way I can make me collection view circular
this is my collectionView code
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell =
collectionView.dequeueReusableCell(withReuseIdentifier:
"CellName", for: indexPath as IndexPath) as! CellName
let gigModel = self.datasoruce?[indexPath.row]
cell.lblTitle.text = gigModel?.title
cell.btnPrice.setTitle(gigModel?.getPriceAccordingToGigType(),
for: .normal)
cell.itemImageView.sd_setImage(with: URL(string:
(gigModel?.getPhotoPath())!), placeholderImage:
UIImage.init(named: "place_holder"))
cell.itemImageView.layer.cornerRadius = 10.0
if Utilities.isValidString(object: gigModel?.adminId as
AnyObject) {
cell.btnStar.isHidden = false
}
else {
cell.btnStar.isHidden = true
}
return cell
}
and I want this to be circular list.
I tried to create sample project and it was pretty simple, here is example code how you can implement "infinite" scroll
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var array: [Any] = [0,1,2,3,4,5,6,7,8,9]
override func viewDidLoad() {
super.viewDidLoad()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Int(Int16.max) // Int.max cause crash
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCell
let correctIndex = indexPath.row >= array.count ? indexPath.row % array.count : indexPath.row
cell.nameLabel.text = "\(array[correctIndex])"
return cell
}
}
Hope it will help you
//Use Below code to get next cell.
func scrollToNextCell(){
//get Collection View Instance
let collectionView:UICollectionView;
//get cell size
let cellSize = CGSizeMake(self.view.frame.width, self.view.frame.height);
//get current content Offset of the Collection view
let contentOffset = collectionView.contentOffset;
//scroll to next cell
collectionView.scrollRectToVisible(CGRectMake(contentOffset.x + cellSize.width, contentOffset.y, cellSize.width, cellSize.height), animated: true);
}
Im making a three view controller project with the first two views are collectionViews. The selected cell will load second view controller with segue and another array depending on which index was selected on first main view. Can anyone point me in the right direction on how to tie a data to load in the second collection view.
import UIKit
class ViewController: UIViewController {
#IBOutlet private weak var collectionView: UICollectionView!
var collectionData = ["cell1", "cell2", "cell3", "cell4", "cell5", "cell6", "cell7", "cell8"]
override func viewDidLoad() {
super.viewDidLoad()
let height = (view.frame.size.width / 2.76)
let width = view.frame.size.width / 1
let layout = collectionView.collectionViewLayout as!
UICollectionViewFlowLayout
layout.itemSize = CGSize(width: width, height: height)
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
if let label = cell.viewWithTag(100) as? UILabel {
label.text = collectionData[indexPath.row]
}
return cell
}
didSelectItemAt indexPath: IndexPath) {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "BannerSegue" {
if let _ = segue.destination as? BannerSelection, let _ = sender as? IndexPath {
}
}
}
}
that is the main view controller. then it has a segue to this view
import UIKit
class BannerSelection: UIViewController {
#IBOutlet weak var collection2: UICollectionView!
var BannerData = ["bannerA1", "bannerA2", "bannerA3", "bannerA4", "bannerA5", "bannerA6", "bannerA7", "bannerA8", "bannerA9", "bannerA10", "bannerA11", "bannerA12"]
var selection: String!
override func viewDidLoad() {
super.viewDidLoad()
let height = (view.frame.size.width / 3.76)
let width = view.frame.size.width / 1
let layout = collection2.collectionViewLayout as!
UICollectionViewFlowLayout
layout.itemSize = CGSize(width: width, height: height)
}
}
extension BannerSelection: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return BannerData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let bannercell = collectionView.dequeueReusableCell(withReuseIdentifier: "BannerSelectionCell", for: indexPath)
if let label = bannercell.viewWithTag(1) as? UILabel {
label.text = BannerData[indexPath.row]
}
return bannercell
}
func collectionView(_ BannerSelection: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
So what im trying to achieve is let's say... index 2 to have an array of "bannerB1, bannerB2" so on and so forth. then i will apply the same technique for the second view controller to populate the final view with a end UIImage. Thank you in advanced!
You can store the data of the first view in the UserDefaults and then retrieve the first vc's data from the second view and load them
As your data Structure is unclear to me, Seems like your data is a dictionary of array like that
dict = [
"cell1" : [Banner1, Banner2,..]
"cell2" : [Apple1, Apple2, ..]
//so on
]
What is the structure of your data structure, let it to be saved in UserDefaults.
UserDefaults.standard.setValue(dict, forKey: "myDataStructure")
while retrieve in second view controller
let array = dict["cell1"] as? Array<String> // depends on the data structure
and populate your viewController.
Very new to code and making a project programmatically. I have my collection view all set up but i cant figure out how to tell a specific cell to navigate to a new collection view or detail view. Very confused and frustrated. can anyone help me or at least point me in the right direction. please dumb it down haha.
this is my main View controller
import UIKit
class HomeController: UICollectionViewController,
UICollectionViewDelegateFlowLayout {
var Legends: [Legend] = {
var select1 = Legend()
select1.thumbnailImageName = "select1thumbnail"
var select2 = Legend()
select2.thumbnailImageName = "select2humbnail"
return[select1, select2]
}()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Choose Selection"
collectionView.backgroundView = UIImageView(image: UIImage(named: "backgroundlogo"))
collectionView?.register(VideoCell.self, forCellWithReuseIdentifier: "cellId")
collectionView.dataSource = self
collectionView.delegate = self
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return Legends.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! VideoCell
cell.legend = Legends[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width:view.frame.height, height: 150)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let select2VC = UIViewController()
navigationController?.navigationBar.tintColor = UIColor.white
navigationController?.pushViewController(select2VC, animated: true)
print("selcected")
}
}
this is the swift file i have for my collection view
import UIKit
class VideoCell: UICollectionViewCell {
var legend: Legend? {
didSet {
thumbnailImageView.image = UIImage(named: (legend?.thumbnailImageName)!)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let thumbnailImageView: UIImageView = {
let imageView = UIImageView()
imageView.backgroundColor = UIColor.darkGray
imageView.image = UIImage(named:"bgcolor")
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}()
func setupViews() {
addSubview(thumbnailImageView)
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-16-[v0]-16-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["v0": thumbnailImageView]))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-1-[v0]-0-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["v0": thumbnailImageView]))
}
}
in a 3rd file i have just this bit of code
import UIKit
class Legend: NSObject {
var thumbnailImageName: String?
}
the bottom code of the main view controller does print out a "selected" but it prints it for every cell... I assume each cell will need its own viewController.swift file? then tell that cell to that swift file to show the contents?? thank you for your time.
No you don't need to create its own viewController.swift file for each cell. You just need to create one detail page screen (one DetailViewController.swift) and you need to pass the detail of selected cell with variables declared on detail view controller.
Like I have done HERE in demo project with your code and result will be:
What I have done is I have added detailViewController in storyboard and also added class file. and didSelectItemAt will look like:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
controller.selectedIndex = indexPath.row //pass selected cell index to next view.
self.navigationController?.pushViewController(controller, animated: true)
}
Here you can pass data with controller.selectedIndex = indexPath.row (Herer I am passing selected index) because selectedIndex is a property of DetailViewController because I have declared it in DetailViewController.swift like
var selectedIndex = 0
And same way you can pass other data as well which is related with selected index.
For more info refer demo project.
If you want check what is sell pressed. You can check what is type cell pressed:
if let cell = tableView.cellForRow(at: indexPath) as? VideoCell {
//check some property and go to new UIViewController or UICollectionViewController
//and transfer data
}
I tried many days to realise this:
I want to add in my UIViewController two different CollectionView.
For example I want to put images in these collectionView
Each CollectionView use its own images.
Is this possible?
I will be very happy if somebody can give me a hand. :)
This is possible, you just need to add each UICollectionView as a subview, and set the delegate and dataSource to your UIViewController.
Here's a quick example. Assuming you have one UICollectionView working, you should be able to adapt this code to your own uses to add a second fairly easily:
let collectionViewA = UICollectionView()
let collectionViewB = UICollectionView()
let collectionViewAIdentifier = "CollectionViewACell"
let collectionViewBIdentifier = "CollectionViewBCell"
override func viewDidLoad() {
// Initialize the collection views, set the desired frames
collectionViewA.delegate = self
collectionViewB.delegate = self
collectionViewA.dataSource = self
collectionViewB.dataSource = self
self.view.addSubview(collectionViewA)
self.view.addSubview(collectionViewB)
}
In the cellForItemAtIndexPath delegate function:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if collectionView == self.collectionViewA {
let cellA = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewAIdentifier) as UICollectionViewCell
// Set up cell
return cellA
}
else {
let cellB = collectionView.dequeueReusableCellWithReuseIdentifier(collectionViewBIdentifier) as UICollectionViewCell
// ...Set up cell
return cellB
}
}
In the numberOfItemsInSection function:
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.collectionViewA {
return 0 // Replace with count of your data for collectionViewA
}
return 0 // Replace with count of your data for collectionViewB
}
Yes--this is entirely possible. You can either assign their respective UICollectionViewDelegates/UICollectionViewDataSources to different classes or subclass the CollectionViews, assigning both the delegate and data source to your current viewController and downcast your reference to collectionView in the delegation methods like so:
#IBOutlet collectionViewA: CustomCollectionViewA!
#IBOutlet collectionViewB: CustomCollectionViewB!
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if let a = collectionView as? CustomCollectionViewA {
return a.dequeueReusableCellWithIdentifier("reuseIdentifierA", forIndexPath: indexPath)
} else {
return collectionView.dequeueReusableCellWithIdentifier("reuseIdentifierB", forIndexPath: indexPath)
}
}
Subclass UICollectionView like this:
class CustomCollectionViewA: UICollectionView {
// add more subclass code as needed
}
class CustomCollectionViewB: UICollectionView {
// add more subclass code as needed
}
You can use the factory design pattern to build two different collection views and return them via functions. Here's my working version for swift 4.
This code goes in a separate helper file:
import UIKit
class collectionViews {
static func collectionViewOne() -> UICollectionView {
let layout = UICollectionViewFlowLayout()
let collectionViewOne = UICollectionView(frame: CGRect(x: 0, y: 20, width: 200, height: 100), collectionViewLayout: layout)
return collectionViewOne
}
static func collectionViewTwo() -> UICollectionView {
let layout = UICollectionViewFlowLayout()
let collectionViewTwo = UICollectionView(frame: CGRect(x: 0, y: 300, width: 200, height: 100), collectionViewLayout: layout)
return collectionViewTwo
}
}
And here is the view controller code:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
let collectionViewOne = collectionViews.collectionViewOne()
let collectionViewTwo = collectionViews.collectionViewTwo()
var myArray = ["1", "2"]
var myArray2 = ["3", "4"]
override func viewDidLoad() {
super.viewDidLoad()
collectionViewOne.delegate = self
collectionViewOne.dataSource = self
collectionViewOne.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
view.addSubview(collectionViewOne)
collectionViewTwo.delegate = self
collectionViewTwo.dataSource = self
collectionViewTwo.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell2")
view.addSubview(collectionViewTwo)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.collectionViewOne {
return myArray.count
} else {
return myArray2.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.collectionViewOne {
let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath)
myCell.backgroundColor = UIColor.red
return myCell
} else {
let myCell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell2", for: indexPath as IndexPath)
myCell2.backgroundColor = UIColor.blue
return myCell2
}
}
}
Result
You can also name the collection views outlets differently (without subclassing):
#IBOutlet weak var collectionView: UICollectionView!
#IBOutlet weak var SecondCollectioView: UICollectionView!
method:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as UICollectionViewCell
if(collectionView == self.SecondCollectioView) {
cell.backgroundColor = UIColor.black
} else {
cell.backgroundColor = self.randomColor()
}
return cell;
}
This is will be an another way.
Here's my working version for swift 5 and Xcode 11:
create outlets for corresponding collectionviews: outlets:
#IBOutlet weak var bgCollectionView: UICollectionView!
#IBOutlet weak var frontCollectionView: UICollectionView!
var arrImages = [String : [UIImage]]()
arrImages is contain like
override func viewDidLoad() {
super.viewDidLoad()
arrImages = [
"frontImg": [//Front UIImage array],
"bgImg": [//Background UIImage array]
]
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let arrImg = arrImages["bgImg"] {
return arrImg.count
} else if let arrImg = arrImages["frontImg"]{
return arrImg.count
}
return 0
}
You can do this two ways
Using CollectionView Outlets
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
if collectionView == self.bgCollectionView{
if let arrImg = arrImages["bgImg"]{
cell.imgView.image = arrImg[indexPath.row]
}
}else{
if let arrImg = arrImages["frontImg"]{
cell.imgView.image = arrImg[indexPath.row]
}
}
return cell
}
Using CollectionView Tag:
Here Background Images collectionview tag is 1 and Front Images collectionview tag is 2.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
if collectionView == collectionView.viewWithTag(1){
if let arrImg = arrImages["bgImg"]{
cell.imgView.image = arrImg[indexPath.row]
}
}else{
if let arrImg = arrImages["frontImg"]{
cell.imgView.image = arrImg[indexPath.row]
}
}
return cell
}
Please Add Tag in CollectionView Like this:
Thank You. Hope It's working for you !!
Swift 5 Answer!
If you try connecting both collectionViews to the same view controller Xcode will throw an error "Outlets cannot connect to repeating content"
Solution:
Head to Storyboard
Connect the first collectionView via outlet, set the delegate/dataSource in viewDidLoad and then add a tag to the second collectionView by heading to the attributes inspector in storyboard and change the value from 0 to 1
Select the secondCollectionView and go to the connections inspector and select delegate and drag the connection to the UIViewController and the same for the dataSource.
Simply check which collectionView is passing through.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == collectionView.viewWithTag(1) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "secondCollectionView", for: indexPath)
return cell
}
else {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "firstCollectionView", for: indexPath) as! HomeMainCollectionViewCell
cell.configureCell()
return cell}
}