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()
}
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 horizontally scrollable UICollectionView with three cells each of which are different subclasses of UICollectionViewCell. Each one of these cells contains a UITableView.
Inside of the first two cells, my table view cells are the same subclasses of UITableViewCell and have just a UIImageView. I use it to set its backgroundColor. Inside of the third cell, my table view's cells are different subclasses of UITableViewCell than in the previous two. They have both a UILabel and a UIImageView. The label has some dummy text, and I set imageView's backgroundColor to some color, again.
In order to follow MVC pattern, I use my UIViewController as a data source and a delegate for both collection view, and table view. Here is the code of UIViewController:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let collectionViewCellId = "collectionViewCell"
let tableViewCellId = "tableViewCell"
let collectionViewCellId2 = "collectionViewCellId2"
let collectionViewCellId3 = "collectionViewCellId3"
let tableViewCellDif = "tableViewCellDif"
var collectionViewIndex: Int?
#IBOutlet weak var collectionView: UICollectionView! {
didSet {
collectionView.delegate = self
collectionView.dataSource = self
collectionView.isPagingEnabled = true
}
}
//MARK: UITableViewDataSource
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let colors: [UIColor] = [.red, .green, .purple, .orange, .blue]
let colors2: [UIColor] = [.blue, .brown, .yellow, .magenta, .cyan]
if collectionViewIndex == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellId, for: indexPath) as! TableViewCell
cell.colorForImageView = colors[indexPath.row]
return cell
} else
if collectionViewIndex == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellId, for: indexPath) as! TableViewCell
cell.colorForImageView = colors2[indexPath.row]
return cell
} else
if collectionViewIndex == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellDif, for: indexPath) as! TableViewCellDifferent
cell.colorForImageView = colors2[indexPath.row]
return cell
} else {
return UITableViewCell()
}
}
}
//MARK: UICollectionViewDataSource
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let identifier: String
if indexPath.item == 0 {
identifier = collectionViewCellId
} else if indexPath.item == 1 {
identifier = collectionViewCellId2
} else if indexPath.item == 2 {
identifier = collectionViewCellId3
} else {
identifier = ""
}
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
return cell
}
}
//MARK: UICollectionViewDelegate
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.item == 0 {
let cell = cell as! CollectionViewCell
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 0
}
if indexPath.item == 1 {
let cell = cell as! CollectionViewCell2
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 1
}
if indexPath.item == 2 {
let cell = cell as! CollectionViewCell3
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 2
print (collectionViewIndex)
}
}
}
//MARK: UICollectionViewDelegateFlowLayout
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let layout = collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}
}
As I stated in a title of the question, nothing happens on a background thread. I, basically, only set the backgroundColor of table view's cells.
The problem is that inside the collection view's third cell (and only inside of there), my table view dequeues its cells only after a minor scroll or tap happens. Here is how it looks like:
I can't figure out why this happens. Maybe, this happens because inside of the third cell of the collection view, my table view's cells are instances of different subclass than inside of the first two?
EDITED
I could solve the problem by reloading the table view before before showing the collection view's each cell but I'm not sure that this is the most efficient solution. Here is the code:
//MARK: UICollectionViewDelegate
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if indexPath.item == 0 {
let cell = cell as! CollectionViewCell
cell.tableView.dataSource = self
cell.tableView.delegate = self
cell.tableView.reloadData()
collectionViewIndex = 0
}
if indexPath.item == 1 {
let cell = cell as! CollectionViewCell2
cell.tableView.dataSource = self
cell.tableView.delegate = self
cell.tableView.reloadData()
collectionViewIndex = 1
}
if indexPath.item == 2 {
let cell = cell as! CollectionViewCell3
cell.tableView.dataSource = self
cell.tableView.delegate = self
cell.tableView.reloadData()
collectionViewIndex = 2
}
}
}
If you know a better way, I would appreciate your help.
I gave this a try, and saw the same results. So, I moved your collection view cell "setup" code from willDisplay cell: to cellForItemAt and it fixed the problem.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item == 0 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellId, for: indexPath) as! CollectionViewCell
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 0
return cell
}
if indexPath.item == 1 {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellId2, for: indexPath) as! CollectionViewCell2
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 1
return cell
}
// if we get here, indexPath.item must equal 2
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewCellId3, for: indexPath) as! CollectionViewCell3
cell.tableView.dataSource = self
cell.tableView.delegate = self
collectionViewIndex = 2
return cell
}
Now, since you're not showing your code for your tableview cells, it's possible there might be another issue, but this worked for me:
class TableViewCell: UITableViewCell {
#IBOutlet var theImageView: UIImageView!
var colorForImageView: UIColor = UIColor.gray {
didSet {
self.theImageView.backgroundColor = colorForImageView
}
}
}
You can try to dequeue CollectionViewCell or TableViewCell explicitly on the main thread
DispatchQueue.main.async {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
}
or
DispatchQueue.main.async {
let cell = tableView.dequeueReusableCell(withIdentifier: tableViewCellDif, for: indexPath) as! TableViewCellDifferent
cell.colorForImageView = colors2[indexPath.row]
}
It could help to wake up the main thread
But in general, it would be much easier if a data source for the table view was inside collection view cell
I have a collection view with sticky headers
flowLayout.sectionHeadersPinToVisibleBounds = true
My issue is that the top half of my header is translucent and when I scroll my cell up I can see the cell scrolling behind the header.
I would like to hide the part of the cell view behind the header. In my image attached I do not want to see the green when it is behind the red. The rest of the behavior I want to keep as is.
The reason I need this is I have a wallpaper image at the very back which I need to be shown
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.alwaysBounceVertical = true
collectionView.register(UINib.init(nibName: EXAMPLE_CELL_REUSE_ID, bundle: nil), forCellWithReuseIdentifier: EXAMPLE_CELL_REUSE_ID)
collectionView.register(UINib.init(nibName: EXAMPLE_HEADER_REUSE_ID, bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: EXAMPLE_HEADER_REUSE_ID)
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.headerReferenceSize = CGSize(width: 400, height: 100)
flowLayout.sectionHeadersPinToVisibleBounds = true
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return sections.count;
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1 //self.sections[section].1;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let exampleCell = collectionView.dequeueReusableCell(withReuseIdentifier: EXAMPLE_CELL_REUSE_ID, for: indexPath) as! MyCellCollectionViewCell;
exampleCell.headerLabel.text = "Cell"
exampleCell.backgroundColor = UIColor.green
return exampleCell;
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
if let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: EXAMPLE_HEADER_REUSE_ID, for: indexPath) as? ExampleHeader {
// header.backgroundColor = UIColor(red: 1.0, green: 0, blue: 0, alpha: 0.5)
return header
} else {
return UICollectionReusableView()
}
}
return UICollectionReusableView()
}
I think the question here may be similar but there are no responses and it is not quite clear if it is the same issue.
Transparent sticky header ui collectionview don't show cells underneath
This worked for me:
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionHeadersPinToVisibleBounds = true
layout.sectionInsetReference = .fromSafeArea
view.backgroundColor = .white
collectionView.anchor(top: view.safeAreaLayoutGuide.topAnchor, leading:
view.leadingAnchor, bottom: view.bottomAnchor, trailing: view.trailingAnchor)
You need to apply mask for all cells that located under header view. Use on scrollViewDidScroll
Tutorial: https://medium.com/#peteliev/layer-masking-for-beginners-c18a0a10743
I have created a very simple setup like yours and it is working fine.
class ViewController: UIViewController, UICollectionViewDataSource
{
#IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad()
{
super.viewDidLoad()
self.collectionView.alwaysBounceVertical = true
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout
{
flowLayout.headerReferenceSize = CGSize(width: 400, height: 100)
flowLayout.sectionHeadersPinToVisibleBounds = true
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int
{
return 10
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
return collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView
{
if kind == UICollectionElementKindSectionHeader
{
return collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "rview", for: indexPath)
}
return UICollectionReusableView()
}
}
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;
}
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}
}