Collection View inside Table View Cell - ios

I want to create collection view inside the table view cell for horizontal scrolling of elements. But I have the problem how to fill right my collection views. I need a way to connect collection views with my data.
How can I get and loop through Table View Cells to find needed collection view and return the cells with data?

below is a general example of how you can pass data to collection views inside your table view cell. Also this link is a youtube tutorial on this subject.
Models:
class ListOfParents: NSObject {
var parents:[Parent]?
}
class Parent: NSObject {
var children: [Child]?
static func fetchParents(_ completionHandler: #escaping (ListOfParents) -> ()) {
//fetch parents data
}
}
class Child: NSObject {
}
TableView cell:
class CustomTableViewController: UITableViewController {
var listOfParents: ListOfParents?
override func viewDidLoad() {
super.viewDidLoad()
Parent.fetchparents { (listOfParents) in
self.listOfParents = listOfParents
}
tableView.register(CustomParentCell.self, forCellReuseIdentifier: "tableCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let parentsCount = listOfParents?.parents?.count else {return 0}
return parentsCount
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! CustomParentCell
cell.parent = listOfParents?.parents?[indexPath.item]
return cell
}
}
Parent cell:
class CustomParentCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {
var parent: Parent? {
didSet {
// set child value here
}
}
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
return collectionView
}()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(CustomChildCell.self, forCellWithReuseIdentifier: "childCellID")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let childrenCount = parent?.children?.count else {return 0}
return childrenCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "childCellID", for: indexPath) as! CustomChildCell
cell.child = parent?.children?[indexPath.item]
return cell
}
}
Child cell:
class CustomChildCell: UICollectionViewCell {
var child: Child?
}

Related

Multiple Horizontal ScrollViews In One Vertical ScrollView in Swift?

I'm trying to achieve one of the most standard layouts in the apps in Swift.
which is basically having Multiple Horizontal ScrollViews In One Vertical ScrollView.
Each of these sub-Horizontal ScrollViews Will hold a few views with images.
Something like this:
what is the best way of achieving this?
P.S. I need to do this using code as the content is pulled via a remote JSON file.
any pointers would be appreciated.
I would do the following.
Use a UITableView for the vertical scroll-view.
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(TableViewCell.self, forCellReuseIdentifier: TableViewCell.identifier)
self.tableView.register(TableViewHeader.self, forHeaderFooterViewReuseIdentifier: TableViewHeader.identifier)
self.tableView.dataSource = self
self.tableView.delegate = self
}
}
extension TableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TableViewCell.identifier,
for: indexPath) as! TableViewCell
return cell
}
}
extension TableViewController {
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: TableViewHeader.identifier)
header?.textLabel?.text = "Header \(section)"
return header
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
}
Use a UICollectionView for the horizontal-scroll-view.
class CollectionView: UICollectionView {
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
self.backgroundColor = .white
self.register(CollectionViewCell.self, forCellWithReuseIdentifier: CollectionViewCell.identifier)
self.dataSource = self
self.delegate = self
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension CollectionView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.identifier,
for: indexPath) as! CollectionViewCell
cell.index = indexPath.row
return cell
}
}
extension CollectionView: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 200, height: 250)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 20
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
class CollectionViewCell: UICollectionViewCell {
static let identifier = "CollectionViewCell"
var index: Int? {
didSet {
if let index = index {
label.text = "\(index)"
}
}
}
private let label: UILabel = {
let label = UILabel()
return label
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.backgroundColor = .red
self.contentView.addSubview(label)
let constraints = [
label.centerYAnchor.constraint(equalTo: contentView.centerYAnchor),
label.centerXAnchor.constraint(equalTo: contentView.centerXAnchor)
]
NSLayoutConstraint.activate(constraints)
label.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Each UITableViewCell contains a UICollectionView (horizontal-scroll-view).
class TableViewCell: UITableViewCell {
static let identifier = "TableViewCell"
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = .white
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let subView = CollectionView(frame: .zero, collectionViewLayout: layout)
self.contentView.addSubview(subView)
let constraints = [
subView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 1),
subView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 1),
subView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 1),
subView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 1)
]
NSLayoutConstraint.activate(constraints)
subView.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Use a UITableViewHeaderFooterView (tableView(_:viewForHeaderInSection:) ) for the title of the horizontal-scroll-view
class TableViewHeader: UITableViewHeaderFooterView {
static let identifier = "TableViewHeader"
}
The code that I have added a complete working example. Just use the TableViewController and you are good to go.
Update
UITableViewCells should have dynamic cell height.
Afte testing, I found out that it is better you use fixed cell-size instead of dynamic because cell might have different height should use UITableView.automaticDimension
Pretty easy with SwiftUI.
You should use a the VStack inside a ScrollView for the vertical one;
and a HStack inside a ScrollView for the horizontal one.
here's an example:
struct ContentView: View {
var body: some View {
ScrollView{
ForEach(0..<10) {_ in
VStack{
ScrollView(.horizontal){
HStack(spacing: 20) {
ForEach(0..<10) {
Text("Item \($0)")
.font(.headline)
.frame(width: 100, height: 100)
.background(Color.gray)
}
}
}
}
}
}
}
}
I made a ForEach to replicate the example items in each stack but you should replace them with your custom views or content. In the picture you uploaded each item is a ZStack with an image and text.
image of compiled code
Create a UITableView for main ViewController.
The views you have to create inside it make their separate ViewController.
For ex:- for mental fitness - Create separate mental fitness ViewController for that
for sleep stories - Create separate Sleep Stories ViewController
Now the climax come here called addChild() method.
Access your all ViewControllers in your main ViewController class and add them in your viewDidLoad() method inside addChild() method.
The last thing you have to do is you just have to add that child ViewControllers in your particular cell as view.
For reference you can check these examples:-
https://www.hackingwithswift.com/example-code/uikit/how-to-use-view-controller-containment
https://www.swiftbysundell.com/basics/child-view-controllers/
Advantage:-
This way you can easily manage your data coming from the server
For example:-
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
//subViewControllers
let firstVC = FirstViewController()
let secondVC = SecondViewController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.addChild(firstVC) //adding childVC here
self.addChild(secondVC)
}
}
UITableViewDataSource and Delegate Method
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? MainCell else {
return UITableViewCell()
}
if indexPath.row == 0 {
cell.contentView.addSubview(firstVC.view)
}
if indexPath.row == 1 {
cell.contentView.addSubview(secondVC.view)
}
return cell
}
}
UITableViewCell Class
class MainCell: UITableViewCell {
}
This way you can easily manage your data which is coming from server. Because it will give you an advantage for showing particular cell data in separate ViewController and much more.

Synchronised Scrolling UICollectionViews in UITableViewCell in Swift

I have the structure like this:
UITableView -> UITableViewCell -> UICollectionView ->
UICollectionViewCell
So what I’m trying to achieve is that I want to make UICollectionViews in UITableViewCells to scroll synchronised. For example when you scroll manually the first UICollectionView on the first row, I want the rest of UICollectionViews to follow, but the Text Labels to stay in the same position all the time. (Please see the image below)
EDIT: I know that I have to use contentOffset somehow, but don’t know how to implement in this case scenario. Any help would be appreciated.
Click to see the image
Click to see the gif
Okay I managed to get this working, Please keep in mind the code is just for the question purposes and contains lot of non-generic parameters and force casting that should be avoided at any cost.
The class for MainViewController containing the tableView:
protocol TheDelegate: class {
func didScroll(to position: CGFloat)
}
class ViewController: UIViewController, TheDelegate {
func didScroll(to position: CGFloat) {
for cell in tableView.visibleCells as! [TableViewCell] {
(cell.collectionView as UIScrollView).contentOffset.x = position
}
}
#IBOutlet var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
}
}
extension ViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as? TableViewCell else { return UITableViewCell() }
cell.scrollDelegate = self
return cell
}
}
The class for your tableViewCell:
class TableViewCell: UITableViewCell {
#IBOutlet var collectionView: UICollectionView!
weak var scrollDelegate: TheDelegate?
override func awakeFromNib() {
super.awakeFromNib()
(collectionView as UIScrollView).delegate = self
collectionView.dataSource = self
}
}
extension TableViewCell: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! CollectionViewCell
cell.imageView.image = #imageLiteral(resourceName: "litecoin.png")
return cell
}
}
extension TableViewCell: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
scrollDelegate?.didScroll(to: scrollView.contentOffset.x)
}
}
The class for the collectionViewCell is irelevant since it's just implementation detail. I will post this solution to github in a second.
Disclaimer: This works just for visible cells. You need to implement the current scroll state for the cells ready for reuse as well. I will extend the code on github.
I came up with a working solution you can test on a playground:
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyCollectionCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
var originatingChange: Bool = false
var observationToken: NSKeyValueObservation!
var offsetSynchroniser: OffsetSynchroniser? {
didSet {
guard let offsetSynchroniser = offsetSynchroniser else { return }
collection.setContentOffset(offsetSynchroniser.currentOffset, animated: false)
observationToken = offsetSynchroniser.observe(\.currentOffset) { (_, _) in
guard !self.originatingChange else { return }
self.collection.setContentOffset(offsetSynchroniser.currentOffset, animated: false)
}
}
}
lazy var collection: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 40, height: 40)
layout.scrollDirection = .horizontal
let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
collection.backgroundColor = .white
collection.dataSource = self
collection.delegate = self
collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
return collection
}()
override func layoutSubviews() {
super.layoutSubviews()
collection.frame = contentView.bounds
contentView.addSubview(collection)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.layer.borderColor = UIColor.black.cgColor
cell.layer.borderWidth = 1
cell.backgroundColor = .white
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
originatingChange = true
offsetSynchroniser?.currentOffset = scrollView.contentOffset
originatingChange = false
}
}
class OffsetSynchroniser: NSObject {
#objc dynamic var currentOffset: CGPoint = .zero
}
class MyViewController : UIViewController, UITableViewDataSource {
var tableView: UITableView!
let offsetSynchroniser = OffsetSynchroniser()
override func loadView() {
let view = UIView()
view.backgroundColor = .white
tableView = UITableView(frame: .zero, style: .plain)
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(tableView)
tableView.dataSource = self
tableView.register(MyCollectionCell.self, forCellReuseIdentifier: "cell")
self.view = view
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyCollectionCell
cell.selectionStyle = .none
cell.collection.reloadData()
cell.offsetSynchroniser = offsetSynchroniser
return cell
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
To make it work with a playground you will see a lot of code that if you are using storyboards or xib is not needed. I hope anyway that the base idea is clear.
Explanation
Basically I created an object called OffsetSynchroniser which has an observable property called currentOffset. Each cell of the tableView accepts an offsetSynchroniser and on didSet they register with KVO for notifications of currentOffset changes.
Each cells also registers to its own collection's delegate and implements the didScroll delegate method.
When any of those collectionView causes this method to be triggered the currentOffset var of the synchroniser is changed and all the cells that are subscribed through KVO will react to the changes.
The Observable object is very simple:
class OffsetSynchroniser: NSObject {
#objc dynamic var currentOffset: CGPoint = .zero
}
then your tableViewCell will have an instance of this object type and on didSet will register with KVO to the var currentOffset:
var originatingChange: Bool = false
var observationToken: NSKeyValueObservation!
var offsetSynchroniser: OffsetSynchroniser? {
didSet {
guard let offsetSynchroniser = offsetSynchroniser else { return }
collection.setContentOffset(offsetSynchroniser.currentOffset, animated: false)
observationToken = offsetSynchroniser.observe(\.currentOffset) { (_, _) in
guard !self.originatingChange else { return }
self.collection.setContentOffset(offsetSynchroniser.currentOffset, animated: false)
}
}
}
The originatingChange variable is to avoid that the collectionView that is actually initiating the offset change will react by causing the offset to be re-set twice.
Finally, always in your TableViewCell, after registering itself as collectionViewDelegate you will implement the method for didScroll
func scrollViewDidScroll(_ scrollView: UIScrollView) {
originatingChange = true
offsetSynchroniser?.currentOffset = scrollView.contentOffset
originatingChange = false
}
In here we can change the currentOffset of the synchroniser.
The tableViewController will at this point just have the ownership for the synchroniser
class YourTableViewController: UItableViewController { // or whatever ViewController contains an UITableView
let offsetSynchroniser = OffsetSynchroniser()
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyCollectionCell
...
cell.offsetSynchroniser = offsetSynchroniser
return cell
}
}
The best way I can think of off the top of my head to do something like this would be to store all of your collectionViews in a collection object. You can then use the UIScrollView's scrollViewDidScroll delegate method from those collectionViews. Just make sure you have your delegate set correctly.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
for view in collectionViewCollection where view.scrollView != scrollView{
view.scrollView.contentOffset = scrollView.contentOffset
}
}
This is untested code, so not a complete answer but it should get you started.

Unable to create cell in collectionview?

I want to add a UICollectionView inside a table view cell.For this purpose, i have created below files.
CollectionCell:
class CollectionCell: UICollectionViewCell {
#IBOutlet weak var lblName: UILabel!
#IBOutlet weak var imgCell: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
I have also created a CollectionCell.xib
CollectionView.swift
class CollectionView: UIView {
#IBOutlet weak var collectionview: UICollectionView!
var arrItems:[String] = []
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
func configureCollectionView()
{
collectionview.register(CollectionCell.self, forCellWithReuseIdentifier: "CollectionCell")
collectionview.delegate = self
collectionview.dataSource = self
}
func setCollectionViewDatasource(arrItems:[String])
{
self.arrItems = arrItems
self.collectionview.reloadData()
}
static func initiateView()->CollectionView
{
let nib = UINib(nibName: "CollectionView", bundle: nil)
let view = nib.instantiate(withOwner: nil, options: nil)[0] as! CollectionView
return view
}
}
extension CollectionView:UICollectionViewDelegate
{
}
extension CollectionView:UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrItems.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:CollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
cell.lblName.text = arrItems[indexPath.row]
return cell
}
}
I have also created CollectionView.xib
Now as i want to add a collectionview inside a tableview cell for that purpose i have created a cutom tableview cell class as CustomTableCell
class CustomTableCell: UITableViewCell {
var view = CollectionView()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
print("ceonstatructir init")
// insitate a nib
view = CollectionView.initiateView()
view.configureCollectionView()
contentView.addSubview(view)
view.setCollectionViewDatasource(arrItems: ["firest","second","thierd"])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setDataSource(arrItems:[String])
{
//view.setCollectionViewDatasource(arrItems: arrItems)
}
}
Now i have created a mainViewController to show the data on tableview so i have crteated viewcontroller.swift
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableview: UITableView!
let sectionArray = ["First","Second","Third","Fourth","Fifth"]
let collectionArray = [["First","Second","Third"],["First","Second","Third"],["First","Second","Third"],["First","Second","Third"],["First","Second","Third"]]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableview.register(CustomTableCell.self, forCellReuseIdentifier: "TableCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in tableView: UITableView) -> Int {
return sectionArray.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sectionArray[section]
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:CustomTableCell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as! CustomTableCell
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let cell:CustomTableCell = cell as! CustomTableCell
let dataSource = collectionArray[indexPath.section]
cell.setDataSource(arrItems:dataSource)
}
}
Now i am trying to send datasource to my collectionview when tableviewcell is just created.But i am getting crash in cellForItemAtIndexPath in collectionview.I am getting cell as nil in cellForItemAyIndexPath.Please tell me what is the issue with it.
In Collectionview.swift change this function
func configureCollectionView()
{
let nib = UINib(nibName: "CollectionCell", bundle: nil)
collectionview.register(nib, forCellWithReuseIdentifier: "cell")
collectionview.delegate = self
collectionview.dataSource = self
}
In cellforItemat change this line
let cell:CollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
to
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionCell

uicollectionview not showing cells swift

I got my data from a url as json string. in my codes, titles variable is an array of my url images.
private let reuseIdentifier = "cell_supporters"
class SupportersCollectionViewController: UICollectionViewController {
var ids = [String]()
var titles = [String]()
#IBOutlet var collection_supporters: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collection_supporters.delegate = self
// Register cell classes
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
getSupporters()
}
// MARK: UICollectionViewDataSource
// override func numberOfSections(in collectionView: UICollectionView) -> Int {
// // #warning Incomplete implementation, return the number of sections
// return 1
// }
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return self.titles.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! SupportersCollectionViewCell
print("Hello collectionView")
let url_img = URL(string: self.titles[indexPath.row])!
print(url_img)
cell.img_logo.af_setImage(
withURL: url_img
)
return cell
}
func getSupporters() {
RestApiManager.sharedInstance.getSupporters { (json: JSON) in
if let results = json.array {
for entry in results {
// print(entry["title"])
//self.ids.append(entry["id"].string!)
self.titles.append(entry["title"].string!)
}
print(self.titles.count)
DispatchQueue.main.async{
self.collection_supporters.reloadData()
}
}
}
}
}
in my code :
print(self.titles.count) // it shows 5
but:
print("Hello collectionView") // not show anything !
If you're using the default UICollectionViewFlowLayout class for the layout you can try implementing the delegate method that returns the size of each item in the collectionView. The UICollectionView doesn't call the cellForItemAt dataSource method at all if it doesn't have the size information or if they're zero.
Try adding this:
extension SupportersCollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 40, height: 40) // Return any non-zero size here
}
}
Dont register cell classes. Delete following line from viewDidLoad function :
self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
Add this line in your ViewDidLoad() method:
self.collectionView!.delegate = self
Change it to this:
private let reuseIdentifier = "cell_supporters"
class SupportersCollectionViewController: UICollectionViewController {
var ids = [String]()
var titles = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.register(SupportersCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
getSupporters()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return self.titles.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! SupportersCollectionViewCell
print("Hello collectionView")
let url_img = URL(string: self.titles[indexPath.row])!
print(url_img)
cell.img_logo.af_setImage(
withURL: url_img
)
return cell
}
func getSupporters() {
RestApiManager.sharedInstance.getSupporters { (json: JSON) in
if let results = json.array {
for entry in results {
// print(entry["title"])
//self.ids.append(entry["id"].string!)
self.titles.append(entry["title"].string!)
}
print(self.titles.count)
DispatchQueue.main.async{
self.collectionView!.reloadData()
}
}
}
}
}
First, you don't required this:
#IBOutlet var collection_supporters: UICollectionView!
Because your view controller is inherited from UICollectionViewController
Also I changed the register of the UICollectionViewCell class to this so it won't crash when you the cells are created:
self.collectionView!.register(SupportersCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

UICollectionView in a UICollectionViewCell

I am interested in having a collectionview as a part of a collection view cell but for some reason cannot figure out how this would be done. Where would I implement the necessary methods for the cells collectionview?
There's an article that Ash Furrow wrote that explains how to put an UICollectionView inside an UITableViewCell. It's basically the same idea when using it inside an UICollectionViewCell.
Everything is done programatically. No storyboards.
I added a UICollectionView inside my UICollectionViewCell. I also show how to add again a UICollectionViewCell inside the created UICollectionView to have this result
import UIKit
class CategoryCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
private let cellId = "cell"
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let appsCollectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
return collectionView
}()
func setupViews() {
backgroundColor = .blue
addSubview(appsCollectionView)
appsCollectionView.delegate = self
appsCollectionView.dataSource = self
appsCollectionView.register(AppCell.self, forCellWithReuseIdentifier: cellId)
addConstrainstWithFormat("H:|-8-[v0]-8-|", views: appsCollectionView)
addConstrainstWithFormat("V:|[v0]|", views: appsCollectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
return cell
}
}
class AppCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews(){
backgroundColor = .red
}
}
My UICollectionViewController
import UIKit
class FeaturedAppsController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let cellId = "cell"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
collectionView?.backgroundColor = .white
collectionView?.register(CategoryCell.self, forCellWithReuseIdentifier: cellId)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(view.frame.width, 150)
}
}
The whole explanation can be found and was developed by "Let´s build that app": https://www.youtube.com/watch?v=Ko9oNhlTwH0&list=PL0dzCUj1L5JEXct3-OV6itP7Kz3tRDmma
This is too late for this answer but it might help others. This is an example of UICollectionView inside a UICollectionViewCell.
Lets start by having a mainCollectionView. Then on each cell of this collection create and initialize a new UICollectionView and right place to do that is in this following delegate of UICollectionView
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath)
e.g I initialize the MainCollectionViewCell here and then MainCollectionViewCell handles the logic to create a new UICollectionView
guard let collectionViewCell = cell as? MainCollectionViewCell else { return }
collectionViewCell.delegate = self
let dataProvider = ChildCollectionViewDataSource()
dataProvider.data = data[indexPath.row] as NSArray
let delegate = ChildCollectionViewDelegate()
collectionViewCell.initializeCollectionViewWithDataSource(dataProvider, delegate: delegate, forRow: indexPath.row)
collectionViewCell.collectionViewOffset = storedOffsets[indexPath.row] ?? 0
Here is the initializer on MainCollectionViewCell that creates a new UICollectionView
func initializeCollectionViewWithDataSource<D: protocol<UICollectionViewDataSource>,E: protocol<UICollectionViewDelegate>>(dataSource: D, delegate :E, forRow row: Int) {
self.collectionViewDataSource = dataSource
self.collectionViewDelegate = delegate
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .Horizontal
let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: flowLayout)
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseChildCollectionViewCellIdentifier)
collectionView.backgroundColor = UIColor.whiteColor()
collectionView.dataSource = self.collectionViewDataSource
collectionView.delegate = self.collectionViewDelegate
collectionView.tag = row
self.addSubview(collectionView)
self.collectionView = collectionView
collectionView.reloadData()
}
Hope that helps !!
I did an example for this and put in on github. It demonstrates the use UICollectionView inside a UICollectionViewCell.
https://github.com/irfanlone/Collection-View-in-a-collection-view-cell
Easiest solution for collectionview inside collectionview using storyboard and Swift 5
Please refer this link for nested collectionview example
import UIKit
class ParentViewController:UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
//MARK: Declare variable
//MARK: Decalare outlet
#IBOutlet weak var outerCollectionView: UICollectionView!
#IBOutlet weak var pageControl: UIPageControl!
let outerCount = 4
//MARK: Decalare life cycle methods
override func viewDidLoad() {
super.viewDidLoad()
pageControl.numberOfPages = outerCount
}
//MARK: Collection View delegate methods
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return outerCount
}
//MARK: Collection View datasource methods
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "OuterCell", for: indexPath) as! OuterCollectionViewCell
cell.contentView.backgroundColor = .none
return cell
}
//MARK:- For Display the page number in page controll of collection view Cell
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let visibleRect = CGRect(origin: self.outerCollectionView.contentOffset, size: self.outerCollectionView.bounds.size)
let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY)
if let visibleIndexPath = self.outerCollectionView.indexPathForItem(at: visiblePoint) {
self.pageControl.currentPage = visibleIndexPath.row
}
}
}
class OuterCollectionViewCell: UICollectionViewCell ,UICollectionViewDataSource,UICollectionViewDelegate {
#IBOutlet weak var InnerCollectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
InnerCollectionView.delegate = self
InnerCollectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
6
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "InnerCell", for: indexPath) as! InnerCollectionViewCell
cell.contentView.backgroundColor = .green
return cell
}
}
class InnerCollectionViewCell: UICollectionViewCell{
}

Resources