I want a TableView with 5 CollectionViews one by one. The Collection Views must display images that scroll horizontally. I followed this tutorial: https://ashfurrow.com/blog/putting-a-uicollectionview-in-a-uitableviewcell-in-swift/
But I want images scrolling in my CollectionView. I don't know how to do that.
Here is my sample code:
import UIKit
class ViewController1: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDelegateFlowLayout {
#IBOutlet var tableView: UITableView!
var images = [UIImage(named:"banner2"),UIImage(named:"banner1"),UIImage(named:"banner3"),UIImage(named:"banner4"),UIImage(named:"banner5")]
var storedOffsets = [Int: CGFloat]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath) as! Cell2
cell.frame = CGRect(x: 0, y: 28, width: 375, height: 202)
cell.myCollection.reloadData()
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let tableViewCell = cell as? Cell2 else { return }
tableViewCell.setCollectionViewDataSourceDelegate(self, forRow: indexPath.row)
tableViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let tableViewCell = cell as? Cell2 else { return }
storedOffsets[indexPath.row] = tableViewCell.collectionViewOffset
}
}
extension ViewController1: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return images.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! Cell1
cell.image.image = images[(indexPath as NSIndexPath).row]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Collection view at row \(collectionView.tag) selected index path \(indexPath)")
}
}
import UIKit
class Cell1: UICollectionViewCell {
#IBOutlet var image: UIImageView!
override init(frame: CGRect) {
super.init(frame: frame)
image.frame = CGRect(x: 0, y: 0, width: 175, height: 175) // Here I get exc_bad_instruction (code=exc_i386_invop subcode=0x0) warning
contentView.backgroundColor = UIColor.green
self.contentView.addSubview(image)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
import UIKit
class Cell2: UITableViewCell {
#IBOutlet var myCollection: UICollectionView!
override func awakeFromNib() {
myCollection.frame = CGRect(x: 0, y: 28, width: 375, height: 202)
}
}
extension Cell2 {
func setCollectionViewDataSourceDelegate<D: UICollectionViewDataSource & UICollectionViewDelegate>(_ dataSourceDelegate: D, forRow row: Int) {
self.myCollection.delegate = dataSourceDelegate
self.myCollection.dataSource = dataSourceDelegate
myCollection.tag = row
myCollection.setContentOffset(myCollection.contentOffset, animated:false) // Stops collection view if it was scrolling.
let layout = UICollectionViewFlowLayout.init()
layout.scrollDirection = .horizontal
layout.sectionInset = UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 0)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.itemSize = CGSize(width: 182, height: 182)
myCollection = UICollectionView.init(frame: myCollection.frame, collectionViewLayout: layout)
myCollection.register(Cell1.self, forCellWithReuseIdentifier: "cell1")
self.contentView.addSubview(myCollection)
myCollection.reloadData()
}
var collectionViewOffset: CGFloat {
set { myCollection.contentOffset.x = newValue }
get { return myCollection.contentOffset.x }
}
}
A pink TableView (I set the colour) and black CollectionView(Again, I set the colour) I can't view my images or my CollectionViewCells that I have set as greenColor. And when touch in the pink part or try scroll I get the error: fatal error: unexpectedly found nil while unwrapping an Optional value with the warning - exc_bad_instruction (code=exc_i386_invop subcode=0x0)
Can someone tell me how I can do this? Thanks in advance
I use Xcode 8 and Swift 3.
I have snippet in OBJECTIVE- C , i think you have to convert into swift 3.0
Here is my code
You can try it
tablecell cellForRowAtIndexPath
static NSString *CellIdentifier = #"cell3";
CollectionViewTableCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CollectionViewTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.headerLabel.text = #"DISH TYPE";
cell.collectionView.delegate = self;
cell.collectionView.dataSource = self;
cell.collectionView.tag = indexPath.row;
[cell.collectionView reloadData];
and collection view cellForItemAtIndexPath
if(collectionView.tag == 4){
FIPhotoCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"foodTagCell" forIndexPath:indexPath];
NSDictionary *dic = [arrAmenities objectAtIndex:indexPath.row];
NSMutableDictionary *dic1 = [selectedAmenities objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:[dic valueForKey:#"ImageURL"]];
[cell.photoImage sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:#""]];
return cell;
}
Related
I have the Main View Controller which has a collection view with its collection view cells each initialized as a tableView to serve multiple rows inside of that collection view cell. If you're getting confused, below is the snapshot of the current state.
The problem is when I try to tap a tableView row cell to open another view controller, It fails and a selected state of table view cell is shown.
Here is the snapshot.
//HomeCollectionViewCell.swift
class HomeCollectionViewCell: UICollectionViewCell {
override func layoutSubviews() {
super.layoutSubviews()
setUpCellView()
}
func setUpCellView() {
let frame = CGRect(x:20, y:20, width: bounds.width - 40, height: 600)
let cell = CellView(frame: frame)
contentView.addSubview(cell)
}
}
//CellView.swift
class CellView: UITableView {
let quoteCell = "QuoteCell"
let newsCell = "NewsCell"
let articleCell = "ArticleCell"
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: .grouped)
self.layer.cornerRadius = 15
self.backgroundColor = .white
self.dataSource = self
self.delegate = self
self.register(QuoteTableViewCell.self, forCellReuseIdentifier: quoteCell)
self.register(NewsTableViewCell.self, forCellReuseIdentifier: newsCell)
self.register(ArticleTableViewCell.self, forCellReuseIdentifier: articleCell)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CellView: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 0: return 35
case 1: return 140
case 2: return 100
case 3: return 140
default: return 0
}
}
}
extension CellView: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return categories[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0: let cell = tableView.dequeueReusableCell(withIdentifier: dateCell)
cell?.textLabel?.text = "Today"
cell?.textLabel?.font = UIFont.systemFont(ofSize: 30, weight: UIFont.Weight.heavy)
return cell!
case 1: let cell = tableView.dequeueReusableCell(withIdentifier: quoteCell) as! QuoteTableViewCell
return cell
case 2: let cell = tableView.dequeueReusableCell(withIdentifier: newsCell) as! NewsTableViewCell
return cell
case 3: let cell = tableView.dequeueReusableCell(withIdentifier: articleCell) as! ArticleTableViewCell
return cell
default: let cell = tableView.dequeueReusableCell(withIdentifier: commonCell)
cell?.textLabel?.text = "LOL"
return cell!
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch indexPath.section {
case 0: print("Date Selected")
case 1: print("Quote Selected")
case 2: print("News Selected")
case 3: let homeViewController = HomeViewController()
let articleDetailViewController = ArticleDetailViewController()
//homeViewController.show(articleDetailViewController, sender: homeViewController)//homeViewController.navigationController?.pushViewController(articleDetailViewController, animated: true)
homeViewController.present(articleDetailViewController, animated: true, completion: nil)
print("Article selected")
default: print("LOL")
}
}
}
//HomeViewController.swift
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupNavBar()
view.addSubview(collectionView)
setUpConstraints()
configure(collectionView: collectionView)
}
func setUpConstraints() {
_ = collectionView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 10, leftConstant: 10, bottomConstant: 10, rightConstant: 10, widthConstant: 0, heightConstant: 0)
collectionView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
lazy var collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let cv = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
cv.translatesAutoresizingMaskIntoConstraints = false
cv.alwaysBounceVertical = true
cv.clipsToBounds = true
cv.showsHorizontalScrollIndicator = false
cv.showsVerticalScrollIndicator = false
cv.backgroundColor = .clear
cv.isHidden = false
return cv
}()
}
private let reuseIdentifier = "Cell"
extension HomeViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
internal func configure(collectionView: UICollectionView) {
collectionView.register(HomeCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 7
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! HomeCollectionViewCell
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 600)
}
}
Please tell where I'm doing wrong or What approach should I use?
Note- No use of storyboards/IB. Done things programmatically only.
Give identifiers("HomeViewController" and "ArticleDetailViewController") to view controllers and try below code in didSelectRow().
case 3:
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let sourceViewController = storyboard.instantiateViewController(withIdentifier: "HomeViewController") as? HomeViewController
let destinationViewController = storyboard.instantiateViewController(withIdentifier: "ArticleDetailViewController") as? ArticleDetailViewController
let navigator: UINavigationController = sourceViewController as! UINavigationController
navigator.pushViewController(destinationViewController!, animated: true)
From what have you done, I want to point out that its not a good idea to present UIViewController from UView. You must write some custom delegates which will get fired once someone taps on those cells in the custom CellView class. Those delegates must be implemented in the view controller that contains the tableview. From the UIViewController you must write the code to present the new viewcontrollers.
I have a UITableView which has 2 sections. In section 1 is a static cell which has a horizontal collectionView inside it.
My question is how do I reference the collectionView in the Controller to reload the collectionView...
Here is my code:
TableView Controller
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "collectionCellID", for: indexPath) as! CollectionTableViewCell
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCellID", for: indexPath) as! TableCell
return cell
}
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
if let cell = cell as? CollectionTableViewCell {
cell.collectionView.delegate = self
cell.collectionView.dataSource = self
cell.collectionView.contentInset = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
}
}
}
TableView Cell
class CollectionTableViewCell: UITableViewCell {
#IBOutlet weak var collectionView: UICollectionView!
}
CollectionView extension
extension MyController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return cell
}
Data call in TableViewController
public func getData() {
ref.observe(.childAdded, with: { (snapshot) in
self.data.append(snapshot)
}
DispatchQueue.main.async {
//MARK: - collectionView.reloadData() <- not available
}
}
})
}
Call the table view's cellForRow(at:) to get a reference to the cell at section 0 row 0, cast that reference to a CollectionTableViewCell, and refer to its collectionView.
I had a tough time to configure the same issue (https://stackoverflow.com/a/45618501/3400991) . Here is few points regarding this :
Your Controller should conforms UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
Create CollectionView cell and set its custom class into CollectionView cell .
Tableview dont have any idea about how much height its cell needed to render complete collectionview data inside tableview cell so you have to use this :
yourTableView.rowHeight = UITableViewAutomaticDimension
yourTableView.estimatedRowHeight = 90
Set Height of Tableview accordingly :
// since Collectionview explicitly telling its Parent to provide height
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//Checking MIME Type
if condition for collectionview cell {
// set here
}
//Normal autolayout cell
else {
return UITableViewAutomaticDimension
}
}
Make Collectionview reference in Tableview Custom Cell class :
class customTableViewCell: UITableViewCell
{
#IBOutlet weak var collectionview: UICollectionView
}
Inside Tableview willDisplayCell :
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.collectionview.delegate = self
cell.collectionview.datasource = self
//Reload it also
cell.collectionview.reloadData()
}
So what I ended up doing was creating a Header View for the table and adding a collectionView to it.
func configureHeaderView() {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.sectionInset = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 105), collectionViewLayout: layout)
collectionView.backgroundColor = UIColor(red: 248/255, green: 248/255, blue: 248/255, alpha: 1)
collectionView.isPagingEnabled = false
collectionView.isUserInteractionEnabled = true
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UINib(nibName: "cell", bundle: nil), forCellWithReuseIdentifier: "cell")
collectionView.showsHorizontalScrollIndicator = false
tableView.tableHeaderView = collectionView
}
Then from anywhere I can now access:
DispatchQueue.main.async {
self?.collectionView.reloadData()
}
I'm trying to build a collectionView that can expand multiple cells after they've been selected/tapped or collapsed when they are deselected, everything works fine when the cells remain on the screen, but once the expanded cells go off screen, I get unexpected behaviour.
For example if I select a cell with IndexPath 0 and then scroll down, tap on cell with IndexPath of 8, scroll back to cell with IndexPath 0 (it's already collapsed), I would tap on it and scroll back to the cell with IndexPath 8 and tap on it again it expands + cell with IndexPath 10 would expand too.
The CollectionView has been implemented programmatically as well the UICollectionViewCell has been subclassed.
ViewController that holds the UICollectionView:
import UIKit
class CollectionViewController: UIViewController {
// MARK: - Properties
fileprivate var collectionView: UICollectionView!
var manipulateIndex: NSIndexPath? {
didSet {
collectionView.reloadItems(at: collectionView.indexPathsForSelectedItems!)
}
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.backgroundColor = UIColor.white
self.view.addSubview(collectionView)
}
}
// MARK: - UICollectionViewDataSource
extension CollectionViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 13
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
cell.textLabel.text = "\(indexPath.item)"
cell.backgroundColor = UIColor.orange
return cell
}
}
// MARK: - UICollectionViewDelegate
extension CollectionViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
let cell = collectionView.cellForItem(at: indexPath) as! CustomCell
cell.expanded = !cell.expanded
manipulateIndex = indexPath as NSIndexPath
return false
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension CollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if let cell = collectionView.cellForItem(at: indexPath) as? CustomCell {
if cell.expanded == true {
return CGSize(width: self.view.bounds.width - 20, height: 300)
}
if cell.expanded == false {
return CGSize(width: self.view.bounds.width - 20, height: 120.0)
}
}
return CGSize(width: self.view.bounds.width - 20, height: 120.0)
}
}
And the subclassed custom UICollectionViewCell:
import UIKit
class CustomCell: UICollectionViewCell {
var expanded: Bool = false
var textLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
textLabel = UILabel(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height/3))
textLabel.font = UIFont.systemFont(ofSize: UIFont.smallSystemFontSize)
textLabel.textAlignment = .center
contentView.addSubview(textLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Please help and thank you so much to the amazing person, who can help me out! :)
Try this:
Example 1: Expand only one cell at a time
Note: No need to take expanded bool variable in custom cell
var section:Int?
var preSection:Int?
var expand:Bool = false
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 13
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
cell.textLabel.text = "\(indexPath.item)"
cell.backgroundColor = UIColor.orange
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if (self.section != nil) {
self.preSection = self.section
}
self.section = indexPath.row
if self.preSection == self.section {
self.preSection = nil
self.section = nil
}else if (self.preSection != nil) {
self.expand = false
}
self.expand = !self.expand
self.collectionView.reloadItems(at: collectionView.indexPathsForSelectedItems!)
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if self.expand, let row = self.section, row == indexPath.row {
return CGSize(width: self.view.bounds.width - 20, height: 300)
}else{
return CGSize(width: self.view.bounds.width - 20, height: 120.0)
}
}
}
Example 2:
Expand multiple cell
import UIKit
class ViewController: UIViewController {
// MARK: - Properties
fileprivate var collectionView: UICollectionView!
var expandSection = [Bool]()
var items = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.items = ["A","B","C","D","E","F","G","H","J","K"]
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(CustomCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.backgroundColor = UIColor.white
self.expandSection = [Bool](repeating: false, count: self.items.count)
self.view.addSubview(collectionView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CustomCell
cell.textLabel.text = self.items[indexPath.row]
cell.backgroundColor = UIColor.orange
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.expandSection[indexPath.row] = !self.expandSection[indexPath.row]
self.collectionView.reloadItems(at: collectionView.indexPathsForSelectedItems!)
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if self.expandSection[indexPath.row] {
return CGSize(width: self.view.bounds.width - 20, height: 300)
}else{
return CGSize(width: self.view.bounds.width - 20, height: 120.0)
}
}
}
UICollectionView will reuse your cells for multiple objects in your data model. You can't control which cells get reused when during reloadItems You should not assume that the expanded state in a given cell corresponds to the state of your data model. Instead, you should be holding onto the expanded state somehow in your data model and re-setting that in every call to cellForItemAt.
In other words, hold your state in your model and set the cell state in cellForItemAt, don't hold it in the cells themselves.
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}
}
Basically, I am trying to obtain something similar to the result of this : http://ashfurrow.com/blog/putting-a-uicollectionview-in-a-uitableviewcell
how ever, i'm want 2 collectionsViews, 1 in first section and another in 2nd section
how do i achieve this ?
i'm bashing my head in here... each time i try to set delegate and datasource it fails and says i need to register a nib
Also i have no idea how i separate the collection views in it's cellForRowAtIndexPath, how can i see which one is loading ?
how can i get it to load properly so that first section has self.genre and 2nd section has the self.radioStat
this is the error i get when i try to set delegate and datasource for the 2nd time
**Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'could not dequeue a view of kind: UICollectionElementKindCell with identifier CollectionViewCell34 - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'
**
tableViewCellCollectionView.swift
import Foundation
import UIKit
let collectionViewCellIdentifier: NSString = "CollectionViewCell"
class tableViewCellCollectionView: UITableViewCell {
var collectionView: UICollectionView!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
var layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(4, 5, 4, 5)
layout.minimumLineSpacing = 5
layout.itemSize = CGSizeMake(91, 91)
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
self.collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
self.collectionView.registerClass(collectionViewCellTableView.self, forCellWithReuseIdentifier: "CollectionViewCell")
self.collectionView.registerClass(collectionViewCellTableView.self, forCellWithReuseIdentifier: collectionViewCellIdentifier)
self.collectionView.backgroundColor = UIColor.lightGrayColor()
self.collectionView.showsHorizontalScrollIndicator = false
self.contentView.addSubview(self.collectionView)
self.layoutMargins = UIEdgeInsetsMake(10, 0, 10, 0)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
let frame = self.contentView.bounds
self.collectionView.frame = CGRectMake(0, 0.5, frame.size.width, frame.size.height - 1)
}
func setCollectionViewDataSourceDelegate(dataSourceDelegate delegate: protocol<UICollectionViewDelegate,UICollectionViewDataSource>, index: NSInteger) {
self.collectionView.dataSource = delegate
self.collectionView.delegate = delegate
self.collectionView.tag = index
self.collectionView.reloadData()
}
}
tableViewCellCollectionView34.swift
import Foundation
import UIKit
let collectionViewCellIdentifier34: NSString = "CollectionViewCell34"
class tableViewCellCollectionView2: UITableViewCell {
var collectionView2: UICollectionView!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
var layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(4, 5, 4, 5)
layout.minimumLineSpacing = 1
layout.itemSize = CGSizeMake(86, 54)
layout.scrollDirection = UICollectionViewScrollDirection.Vertical
self.collectionView2 = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
self.collectionView2.registerClass(collectionViewCellTableView2.self, forCellWithReuseIdentifier: collectionViewCellIdentifier34)
self.collectionView2.backgroundColor = UIColor.lightGrayColor()
self.collectionView2.showsHorizontalScrollIndicator = false
self.contentView.addSubview(self.collectionView2)
self.layoutMargins = UIEdgeInsetsMake(10, 0, 10, 0)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
let frame = self.contentView.bounds
self.collectionView2.frame = CGRectMake(0, 0.5, frame.size.width, frame.size.height - 1)
}
func setCollectionViewDataSourceDelegate2(dataSourceDelegate delegate: protocol<UICollectionViewDelegate,UICollectionViewDataSource>, index: NSInteger) {
self.collectionView2.dataSource = delegate
self.collectionView2.delegate = delegate
self.collectionView2.tag = index
self.collectionView2.registerClass(collectionViewCellTableView2.self, forCellWithReuseIdentifier: collectionViewCellIdentifier34)
self.collectionView2.reloadData()
}
}
Player.swift
extension Player: UICollectionViewDataSource,UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.radioStat.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: collectionViewCellTableView = collectionView.dequeueReusableCellWithReuseIdentifier(reuseCollectionViewCellIdentifier, forIndexPath: indexPath) as collectionViewCellTableView
var rowData: String = self.genre.objectAtIndex(indexPath.row) as String
cell.title.text = rowData as String
let cell2: collectionViewCellTableView2 = collectionView.dequeueReusableCellWithReuseIdentifier(reuseCollectionViewCellIdentifier2, forIndexPath: indexPath) as collectionViewCellTableView2
let userPost: String = self.radioStat.objectAtIndex(indexPath.row) as String
cell2.pinImage.image = UIImage(named: userPost)
let collectionViewArray = self.sourceArray[collectionView.tag] as NSArray
return cell
}
extension Player {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as UITableViewCell
if (indexPath.section == 0){
var cell2: tableViewCellCollectionView = tableView.dequeueReusableCellWithIdentifier(reuseTableViewCellIdentifier, forIndexPath: indexPath) as tableViewCellCollectionView
return cell2
}else if (indexPath.section == 1){
let cell3: tableViewCellCollectionView2 = tableView.dequeueReusableCellWithIdentifier(reuseTableViewCellIdentifier2, forIndexPath: indexPath) as tableViewCellCollectionView2
return cell3
}
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.section == 0){
if let collectionCell: tableViewCellCollectionView = cell as? tableViewCellCollectionView{
collectionCell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, index: indexPath.row)
}
}
if (indexPath.section == 1){
if let collectionCell2: tableViewCellCollectionView2 = cell as? tableViewCellCollectionView2{
collectionCell2.setCollectionViewDataSourceDelegate2(dataSourceDelegate: self, index: indexPath.row)
}
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (indexPath.section == 0){
return 50
}
if (indexPath.section == 1){
return 450
}else {
return 100
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sourceArray.count
}
}
You need to know which (tableView) section your collectionView relates to. One way to do this would be to subclass UICollectionView and add a tvSection property to it - in the same way that Ash Furrow uses AFIndexedCollectionView to add an index property.
But you seem to be using the collectionView tag in place of his index, presumably to avoid subclassing. If so, a similar dodge would be to use the tag of the tableViewCell's contentView to indicate which section the cell is in. Amend the tableView cellForRowAtIndexPath method to do this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as UITableViewCell
if (indexPath.section == 0){
var cell2: tableViewCellCollectionView = tableView.dequeueReusableCellWithIdentifier(reuseTableViewCellIdentifier, forIndexPath: indexPath) as tableViewCellCollectionView
cell2.contentView.tag = indexPath.section
return cell2
} else if (indexPath.section == 1){
let cell3: tableViewCellCollectionView2 = tableView.dequeueReusableCellWithIdentifier(reuseTableViewCellIdentifier2, forIndexPath: indexPath) as tableViewCellCollectionView2
cell3.contentView.tag = indexPath.section
return cell3
}
cell.contentView.tag = indexPath.section
return cell
}
Because the collectionView is added as a subview of the contentView, you can determine the (tableView) section for a given collectionView using superview.tag. So modify your collectionView's cellForItemAtIndexPath to test this:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let section = collectionView.superview.tag
if section == 0 {
let cell: collectionViewCellTableView = collectionView.dequeueReusableCellWithReuseIdentifier(reuseCollectionViewCellIdentifier, forIndexPath: indexPath) as collectionViewCellTableView
// Now configure from the data...
var rowData: String = self.genre.objectAtIndex(indexPath.row) as String
cell.title.text = rowData as String
return cell
else {
let cell2: collectionViewCellTableView2 = collectionView.dequeueReusableCellWithReuseIdentifier(reuseCollectionViewCellIdentifier2, forIndexPath: indexPath) as collectionViewCellTableView2
// Now configure from the data...
let userPost: String = self.radioStat.objectAtIndex(indexPath.row) as String
cell2.pinImage.image = UIImage(named: userPost)
return cell2
}
}
This will need some polishing; in particular I'm not sure how you wish to map your data (sourceArray, genre and radioStat) to the tableView rows and collectionView items. (I've taken a guess based on your existing code). But this should give you something to work with.