I am trying to achieve a feature that whenever I tap a button from the collectionview at the bottom, the specific value that was tapped will reflect on the collectionview in the middle. So far, I have achieved the bottom collectionview, but I am not sure what is wrong with my code that my new collectionview isn't showing.
import UIKit
class MyButtonCell: UICollectionViewCell{
#IBOutlet weak var buttonOne: UIButton!
#IBOutlet weak var targetButton: UIButton!
var callback: (() -> ())?
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
contentView.layer.borderWidth = 1
contentView.layer.borderColor = UIColor.black.cgColor
}
#IBAction func buttonTapped(_ sender: UIButton) {
callback?()
}
}
class StevenViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
let buttonTitles: [String] = [
"4", "6", "7", "8"
]
var targetButtonTitles: [String] = []
//number array
#IBOutlet var collectionView: UICollectionView!
#IBOutlet weak var targetCollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
targetCollection.delegate = self
targetCollection.dataSource = self
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return buttonTitles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyButtonCell
let targetCell = targetCollection.dequeueReusableCell(withReuseIdentifier: "target", for: indexPath) as! MyButtonCell
// set the button title (and any other properties)
cell.buttonOne.setTitle(buttonTitles[indexPath.item], for: [])
// set the cell's callback closure
cell.callback = {
print("Button was tapped at \(indexPath)")
self.targetButtonTitles.append(self.buttonTitles[indexPath.item])
print(self.targetButtonTitles)
targetCell.targetButton.setTitle(self.targetButtonTitles[indexPath.item], for: [])
// do what you want when the button is tapped
}
return cell
}
}
My storyboard:
What's showing in the simulator:
Try this out.
In your cellForItemAtIndexPath you must return both cells in order to show them both.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyButtonCell
let targetCell = targetCollection.dequeueReusableCell(withReuseIdentifier: "target", for: indexPath) as! MyButtonCell
if collectionView == self.collectionView {
// Setup here your cell
cell.callback = {
print("Button was tapped at \(indexPath)")
self.targetButtonTitles.append(self.buttonTitles[indexPath.item])
print(self.targetButtonTitles)
targetCell.targetButton.setTitle(self.targetButtonTitles[indexPath.item], for: [])
// do what you want when the button is tapped
}
cell.buttonOne.setTitle(buttonTitles[indexPath.item], for: [])
return cell
} else {
// Setup here your targetCell
return targetCell
}
Note that also if you have a different number of sections for each collectionView, you must return them independently.
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.collectionView {
return 1 // Number of sections of your collectionView
}
return 1 // Number of sections of your targetCollection
}
Related
I have an issue with a collectionView inside a TableVieCell. When i tap on a collectionCell, didSelectItemAt doesn´t get called. I have a button in the collectionCell so i tried to disable the user interaction and enable the contentView userInteraction but it didn't work.
The red rectangle is the tableCell and the blue rectangle is the collecionView insede the table view cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "MedCellWithCollection") as? MedCellWithCollection{
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.white.withAlphaComponent(0.0)
cell.selectedBackgroundView = backgroundView
cell.setMedName(name: self.medCatalog[indexPath.row].nombre, uso: self.medCatalog[indexPath.row].uso , array: self.medCatalog[indexPath.row].enfermedades[0].aplicaciones , index: indexPath.row)
cell.layoutIfNeeded()
cell.layoutSubviews()
cell.setNeedsUpdateConstraints()
cell.updateConstraintsIfNeeded()
return cell
}
}
return UITableViewCell()
}
The tableCell
class MedCellWithCollection: UITableViewCell {
//Outlets
#IBOutlet weak var medText: UILabel!
#IBOutlet weak var uso: UILabel!
#IBOutlet weak var arrowIcon: UIImageView!
#IBOutlet weak var CollectionView: UICollectionView!
//Variables
var dosesType:[Aplicacion]?
override func awakeFromNib() {
super.awakeFromNib()
self.collectionViewSetUp()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setMedName(name: String, uso: String, array: [Aplicacion], index: Int){
self.medText.text = name
self.uso.text = uso
self.dosesType = array
self.CollectionView.reloadData()
}
}
extension MedCellWithCollection: UICollectionViewDataSource, UICollectionViewDelegate{
func collectionViewSetUp(){
self.CollectionView.delegate = self
self.CollectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dosesType?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "doseColletion", for: indexPath as IndexPath) as? DoseCollection {
cell.setButtonConfig(doseType: self.dosesType![indexPath.row].metodo , index: indexPath.row)
return cell
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("tapped")
}
}
CollectionCell
import UIKit
class DoseCollection: UICollectionViewCell {
//Outlets
#IBOutlet weak var Button: Button!
//Variables
let constants = Constants()
func setButtonConfig(doseType: String, index: Int){
self.Button.titleLabel?.text = doseType
self.Button.backgroundColor = constants.COLOR_ARRAY[index]
}
override func layoutSubviews() {
super.layoutSubviews()
}
override func layoutIfNeeded() {
super.layoutIfNeeded()
}
}
Potential Solutions:
1) Should be Single Selection for tableView selection property, programmatically it can be done by tableView.allowsSelection = true
2) The class is not the UITableViewDelegate for that table view, though UITableViewController is supposed to set that automatically.
tableView?.delegate = self
3) If the problem arise with UITapGestureRecognizer:
let tap = UITapGestureRecognizer(target: self, action:Selector("dismissKeyboard"))
view.addGestureRecognizer(tap)
tap.cancelsTouchesInView = false
BOL :)
In my case, I want to change the background of the button in other words the background of the cell in the collection view:
class CustomCVCell: UICollectionViewCell {
override var isSelected: Bool {
didSet {
grayBackgroundViewWithImage.image =
isSelected ? UIImage(named: "") : UIImage()
}
}
In the main class where the collection view is stored create this variable:
class CustomViewController: UIViewController {
///save the indexPath of last selected cell
private var lastSelectedIndexPath: IndexPath? }
In viewDidLoad() set this value to false:
customCollectionView.allowsMultipleSelection = false
Further code in data source. In my case, the first cell should be is selected:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomCVCell.cellID(),
for: indexPath) as! CustomCVCell
if indexPath.row == 0 {
lastSelectedIndexPath = indexPath
cell.isSelected = true
}
//update last select state from lastSelectedIndexPath
cell.isSelected = (lastSelectedIndexPath == indexPath)
return cell
}
Further code in the delegate:
///UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard lastSelectedIndexPath != indexPath else { return }
if let index = lastSelectedIndexPath {
let cell = collectionView.cellForItem(at: index) as! CustomCVCell
cell.isSelected = false
}
let cell = collectionView.cellForItem(at: indexPath) as! CustomCVCell
cell.isSelected = true
lastSelectedIndexPath = indexPath
}
I currently have two collectionview, each linked with an array of Strings and are embedded with buttons. I want to make it so that I can select a value on the collectionview at the bottom, then be able to drop that value to a position on the collectionview on the top, by ,again, tapping it . I am not sure how I can update the collectionview, every time I tap a button.
import UIKit
class MyButtonCell: UICollectionViewCell{
#IBOutlet weak var buttonOne: UIButton!
#IBOutlet weak var targetButton: UIButton!
var callback: (() -> ())?
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
contentView.layer.borderWidth = 1
contentView.layer.borderColor = UIColor.black.cgColor
}
#IBAction func buttonTapped(_ sender: UIButton) {
callback?()
}
}
class StevenViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
let buttonTitles: [String] = [
"4", "6", "7", "8"
]
var targetButtonTitles: [String] = [
"", "", "", ""
]
var current:String = ""
#IBOutlet var collectionView: UICollectionView!
#IBOutlet var targetCollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
targetCollection.delegate = self
targetCollection.dataSource = self
collectionView.delegate = self
collectionView.dataSource = self
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return buttonTitles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyButtonCell
let targetCell = targetCollection.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyButtonCell
// set the button title (and any other properties)
if collectionView == self.collectionView {
// Setup here your cell
cell.callback = {
print("Button was tapped at \(indexPath)")
self.targetButtonTitles[indexPath.item] = self.buttonTitles[indexPath.item]
//print(self.targetButtonTitles)
self.current = self.buttonTitles[indexPath.item]
print(self.current)
// do what you want when the button is tapped
}
cell.buttonOne.setTitle(buttonTitles[indexPath.item], for: [])
return cell
} else {
// Setup here your targetCell
cell.callback = {
if self.current != ""{
self.targetButtonTitles[indexPath.item] = self.current
targetCell.targetButton.setTitle(self.targetButtonTitles[indexPath.item], for: [])
}
}
targetCell.targetButton.setTitle(self.targetButtonTitles[indexPath.item], for: [])
return targetCell
}
}
}
I am not sure how I can put that "return targetcell" into the cell.callback or the iBaction
I suggest that you do your logic by the tag of the collection views.
override func viewDidLoad() {
super.viewDidLoad()
collectionView.tag = 1
targetCollection.tag = 2
}
in your delegates you create and return your cells by checking which collection view is asking for the data, for example
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView.tag == 1 {
return buttonTitles.count
} else if collectionView.tag == 2 {
return targetButtonTitles.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView.tag == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyButtonCell
cell.buttonOne.setTitle(buttonTitles[indexPath.item], for: [])
.
.
.
return cell
} else if collectionView.tag == 2 {
let targetCell = targetCollection.dequeueReusableCell(withReuseIdentifier: "myCellID", for: indexPath) as! MyButtonCell
cell.buttonOne.setTitle(targetButtonTitles[indexPath.item], for: [])
.
.
.
return cell
}
}
in your callbacks, move the data around in your two arrays and when you done, reload both collection views.
self.targetButtonTitles[indexPath.item] = self.buttonTitles[indexPath.item]
collectionView.reloadData()
targetCollection.reloadData()
I have a UICollectionViewController called SwipingController that creates a TeamCell and gives it a teamName of "Boston Celtics"
class SwipingController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.backgroundColor = .white
collectionView?.register(TeamCell.self, forCellWithReuseIdentifier: "cellId")
collectionView?.isPagingEnabled = true
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! TeamCell
cell.teamName = "Boston Celtics"
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: view.frame.height)
}
}
However, when I run the code, teamName still prints out as an empty string.
class TeamCell: UICollectionViewCell {
var teamName: String = ""
override init(frame: CGRect) {
super.init(frame: frame)
print(teamName) //this prints nothing
}
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! TeamCell
it inits the cell, and so initially it is empty.
After initialization cell.teamName = "Boston Celtics" is called, actually having no effect
you have to update the name
class TeamCell: UICollectionViewCell {
var teamName: String = ""
override init(frame: CGRect) {
super.init(frame: frame)
print(teamName) //this prints nothing
}
func updateName(name : String) {
self.testName = name
}
}
in collectionview
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! TeamCell
cell.updateName(name : "Boston Celtics")
return cell
}
You are simply looking at teamName too early in the process. By the time cellForItemAt hits the cell.teamName = ... line, the cell’s init method has already been called. So, teamName will always be blank during the init method. But, teamName will be set before the cell appears within the view.
Often cells would just have UIKit controls, such as a UILabel, and you’d set the text of that, e.g.
class TeamCell: UICollectionViewCell {
var teamLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure() {
addSubview(teamLabel)
NSLayoutConstraint.activate([
teamLabel.centerXAnchor.constraint(equalTo: centerXAnchor),
teamLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
])
}
func update(for team: String) {
teamLabel.text = team
}
}
And then
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! TeamCell
cell.update(for: "Boston Celtics")
return cell
}
Please try this :
class TeamCell: UICollectionViewCell {
var teamName : String = "" {
didSet {
print(teamName)
}
}
override func awakeFromNib() {
super.awakeFromNib()
//custom logic goes here
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! TeamCell
cell.teamName = "Boston Celtics"
return cell
}
OR
class TeamCell: UICollectionViewCell {
override func awakeFromNib() {
super.awakeFromNib()
//custom logic goes here
}
func getTeamName(teamName : String)
{
print(teamName)
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! TeamCell
cell.getTeamName(teamName: "Boston Celtics")
return cell
}
in TeamCell class try this
var teamcell = String()
override init(frame: CGRect) {
super.init(frame: frame)
if teamcell != nil {
print(teamName)
}
}
It’s just a matter of order of events. The cell is created, you print, the cell is used in the table view, the team name is assigned.
I have created a carousel view using UPCarouselFlowLayout and it works well. But when the UIButton in the view is clicked, no action occurs. How do I make it so that when the UIButton is clicked, it calls a particular action?
CollectionViewCell:
class MagicCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var magicview: UIView!
#IBOutlet weak var magicimage: UIImageView!
#IBOutlet weak var magiclabel: UILabel!
#IBOutlet weak var magicbutton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
self.magicview.isUserInteractionEnabled = true
// Initialization code
DispatchQueue.main.async {
self.magicview.layer.shadowColor = UIColor.gray.cgColor
self.magicview.layer.shadowOpacity = 0.5
self.magicview.layer.shadowOpacity = 10.0
self.magicview.layer.shadowOffset = .zero
self.magicview.layer.shadowPath = UIBezierPath(rect: self.magicview.bounds).cgPath
self.magicview.layer.shouldRasterize = false
}
}
}
Magic1.swift
import UPCarouselFlowLayout
class Magic1: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
#IBOutlet weak var magiccollection: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
magiccollection.register(UINib.init(nibName: "MagicCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "magiccidentifier")
let floawLayout = UPCarouselFlowLayout()
floawLayout.itemSize = CGSize(width: UIScreen.main.bounds.width - 60.0, height: magiccollection.frame.size.height)
floawLayout.scrollDirection = .horizontal
floawLayout.sideItemScale = 0.8
floawLayout.sideItemAlpha = 1.0
floawLayout.spacingMode = .fixed(spacing: 5.0)
magiccollection.collectionViewLayout = floawLayout
magiccollection.delegate = self
magiccollection.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = sexeducollec.dequeueReusableCell(withReuseIdentifier: "magiccidentifier", for: indexPath) as!MagicCollectionViewCell
if indexPath.row == 0{
cell.magiclabel.text = "Tester title"
cell.sexedimage.image = #imageLiteral(resourceName: "merlin")
}else if indexPath.row == 1{
cell.magiclabel.text = "love is in the air"
}else{
cell.magiclabel.text = "Title - \(indexPath.row + 1)"
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.row == 0{
print("Accio")
}else if indexPath.row == 1{
print("alohamora")
}
}
}
What I'm trying to do is when magicbutton is clicked at indexPath.row == 0 it calls a specific action and when it is clicked at indexPath.row == 1 it calls a specific function.
Try this approach! Also, You can call closure at IBAction
class ViewController: UICollectionViewController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "magiccidentifier", for: indexPath) as? MagicCollectionViewCell {
switch indexPath.row {
case 0:
cell.onCellTouched = { print("Hi")}
default:
cell.onCellTouched = { print("By") }
}
return cell
}
return UICollectionViewCell()
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let item = collectionView.cellForItem(at: indexPath) as? MagicCollectionViewCell
item?.onCellTouched()
}
}
class MagicCollectionViewCell: UICollectionViewCell {
var onCellTouched: () -> Void = { assertionFailure("Cell action didn't set up") }
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = .black
}
}
You are missing an IBAction of your button in MagicCollectionViewCell. So add an action for your button:
#IBAction func buttonAction(_ sender: UIButton) {
}
I have two collection Views in One View Controller, First Collection View have class CollectionCellA with imageA as UIImageView! and labelA as UILabel!. Similarly Second Collection View with class CollectionCellB with imageB and labelB. I tried to run with following swift code but it show just blank(white) screen.
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var imageArroy = [UIImage(named: "1"), UIImage(named: "2"), UIImage(named: "3"), UIImage(named: "5"), UIImage(named: "6")]
var imageArroyB = [UIImage(named: "a"), UIImage(named: "b"), UIImage(named: "c"), UIImage(named: "d"), UIImage(named: "e")]
var labelA: ["Electronics", "Cars", "Pets", "Mobiles", "Food"]
var labelB: ["UK", "Ireland", "India", "Germany", "Other EU"]
#IBOutlet weak var CollectionViewA: UICollectionView!
#IBOutlet weak var CollectionViewB: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
CollectionViewA.delegate = self
CollectionViewB.delegate = self
CollectionViewA.dataSource = self
CollectionViewB.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.CollectionViewA {
return 0 // Replace with count of your data for collectionViewA
}
return 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.CollectionViewA {
let cellA = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCellA", for: indexPath) as! CollectionCellA
// Set up cell
return cellA
}
else {
let cellB = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCellB", for: indexPath) as! CollectionCellB
// ...Set up cell
return cellB
}
}
This code works for Two Collection View in One View Controller with images and label.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.CollectionViewA {
return imageArroy.count
}
return imageArroyB.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.CollectionViewA {
let cellA = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCellA", for: indexPath) as! CollectionCellA
cellA.imageA.image = imageArroyB[indexPath.row]
cellA.labelA.text = labelA[indexPath.row]
// Set up cell
return cellA
}
else {
let cellB = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCellB", for: indexPath) as! CollectionCellB
cellB.imageB.image = imageArroyB[indexPath.row]
cellB.labelB.text = labelB[indexPath.row]
// ...Set up cell
return cellB
}
}
For me below code works like a charm . you should send/assign value in cellForItemAt indexPath
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == self.CollectionViewA {
return imageArroy.count
}
return imageArroyB.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.CollectionViewA {
let cellA = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCellA", for: indexPath) as! CollectionCellA
// Set up cell
cellA.lbl.text = labelA[indexPath.row]
return cellA
}
else {
let cellB = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCellB", for: indexPath) as! CollectionCellB
// ...Set up cell
cellB.lbl.text = labelB[indexPath.row]
return cellB
}
}
}
class CollectionCellA : UICollectionViewCell {
#IBOutlet weak var lbl: UILabel!
}
class CollectionCellB : UICollectionViewCell {
#IBOutlet weak var lbl: UILabel!
}
Add two collection view and connect delegate and data source with view countroller,create collection view cell and connect with cell and outlets
#IBOutlet weak var collectionView2: UICollectionView!
#IBOutlet weak var collectionview1: UICollectionView!
var days = ["Sun","Mon","Tues","Wed","Thur","Frid","Sat"]
var dayTask = [String]()
var task = [["Sun1","Mon1","Tues1","Wed1","Thur1","Frid1","Sat1"],["Sun2","Mon2","Tue2","Wed2"],["Sun3","Mon3","Tues3","Wed3","Thur3","Frid3","Sat3"],["Sun4","Mon4"],["Sun5","Mon5","Tues5","Wed5","Thur5","Frid5","Sat5"],["Sun6","Mon6","Tues6","Wed6"],["Sun7","Mon7","Tues7","Wed7","Thur7"]]
override func viewDidLoad() {
super.viewDidLoad()
dayTask = task[0]
// Do any additional setup after loading the view.
}
Collection view data source and delgate
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == collectionview1{
return days.count
}else{
return dayTask.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell1", for: indexPath) as! CollectionViewCell1
if collectionView == collectionview1{
cell.label.text = days[indexPath.row]
let collectionViewLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
collectionViewLayout?.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 40)
collectionViewLayout?.invalidateLayout()
}else
{
let collectionViewLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
collectionViewLayout?.sectionInset = UIEdgeInsets(top: 10, left: 20, bottom: 0, right: 40)
collectionViewLayout?.invalidateLayout()
cell.label.text = dayTask[indexPath.row]
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == collectionview1{
dayTask = task[indexPath.row]
collectionView2.reloadData()
}
}