i want to make Swift app with CollectionView in Xcode, i have implemented it well and now i want to show some other stuff after some Posts, and i have created Xib and swift file for it. but the problem is when i try to show label in new cell i got this error ,,
i have registered new cell in ViewDidLoad Like this:
collectionView.dataSource = self
collectionView.delegate = self
collectionView.collectionViewLayout = UICollectionViewFlowLayout()
collectionView.register(AdViewCell.self, forCellWithReuseIdentifier: "adCell")
and i have used 300X250 space in AdViewCell and when i load posts i can see the white space of 300X250 size.. look at this
but even when i try to change its background color or anything , nothing happens when app is loaded..
i have connected Label to AdViewCell also..
class AdViewCell: UICollectionViewCell {
#IBOutlet weak var namelbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
please help
Your are using "cell" and "adcell" for the same indexPath.
try this:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.item % 5 == 1 {
let adcell = collectionView.dequeueReusableCell(withReuseIdentifier: "adcell", for: indexPath) as! AdViewCell
return adcell
}else{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MovieCollectionViewCell", for: indexPath) as! MovieCollectionViewCell
return cell
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let indexPath = tableView.indexPathForSelectedRow() //optional, to get from any UIButton for example
let currentCell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell
print(currentCell.textLabel!.text)
Related
My CollectionViewCell imageView is nil
My Cell File is here
class MyTicketsCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var imgTicket: UIImageView!
}
My Controller File Code is here
class MyTicketsCollectionViewController: UICollectionViewController {
var photos: [String] = ["ticket1","ticket2","ticket3","ticket4"]
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.register(MyTicketsCollectionViewCell.self, forCellWithReuseIdentifier: "MyTicketsCollectionViewCell")
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyTicketsCollectionViewCell", for: indexPath) as! MyTicketsCollectionViewCell
cell.imgTicket.image = UIImage(named: photos[indexPath.row])
return cell
}
}
Error is "Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
When I debug it then
cell.imgTicket is nil
How solve this issue?
Try changing your code to
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyTicketsCollectionViewCell", for: indexPath) as! MyTicketsCollectionViewCell
cell.imgTicket.image = UIImage(named: photos[indexPath.row])
return cell
}
You are dequeuing ActiveTicketsCollectionViewCell but the cell is registered under MyTicketsCollectionViewCell.
There is 2 possible solutions here...
1. Might be ActiveTicketsCollectionViewCell have not the property imgTicket or you mention a wrong cell class here as u have mentioned a different cell class name MyTicketsCollectionViewCell so try to write this code.
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyTicketsCollectionViewCell", for: indexPath) as! MyTicketsCollectionViewCell
cell.imgTicket.image = UIImage(named: photos[indexPath.row])
return cell
2. Might be you have missed to connect your property (#IBOutlet weak var imgTicket: UIImageView!) with the Outlet (xib or storyboard).
I am trying to perform a segue from a collection view which is inside a table view cell, the view looks like this
enter image description here
To explain it well, I have a table view, each row has a cell , inside the second row , I have a collection view which includes several products
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell", for: indexPath)
return cell
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemTitle", for: indexPath)
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
return cell
case 3:
let cell = tableView.dequeueReusableCell(withIdentifier: "SectionTitle", for: indexPath)
return cell
case 4:
let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
return cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
return cell
}
}
Inside my ItemCell class I have the following
#IBOutlet weak var collectionView: UICollectionView!
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "singleItemCell", for: indexPath) as! singleItemCell
cell.itemImage.image = images[indexPath.row]
cell.itemImage.contentMode = .scaleAspectFit
return cell
}
I want to perform a segue such as when the user select a cell from the collection view, It takes him to another view controller. How can I do that ?
I tried performSegue but it does not allow me since I am in the cell class
Please any tips ?
In Your ItemCell class make a variable for referencing your ViewController like this:
var productVC:UIVIewController?
while loading TableView Cell set the reference to self like this:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
cell.productVC = self
return cell
default:
let cell = tableView.dequeueReusableCell(withIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
return cell
}
}
then implement the didSelect UICollectionView delegate method in ItemCell Class
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
productVC.performSegue(withIdentifier: "pass your segue identifier here..", sender: nil)
}
protocol ProductCellDelegate: class {
func didChoosedProduct(item: ItemImage)
}
class ProductCell {
#IBOutlet weak var collectionView: UICollectionView!
// Your Model Array
var itemImages: [ItemImages] = [] {
didSet {
self.collectionView.reloadData()
}
// Must set the delegate to your viewcontroller object in tableviewcell cell for rowat indexpath method
weak var delegate: ProductCellDelegate?
override func awakeFromNib() {
self.collectionView.delegate = self
}
}
extension ProductCell: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedItem = self.itemImages[indexPath.row]
self.delegate?.didChoosedProduct(item: selectedItem)
}
}
Implement ProductCellDelegate in your viewcontroller. Call performsegue to navigation.
Implement UICollectionViewDataSource and UICollectionViewDelegate not in tableView cell, but in your ViewController.
You can access to collectionView in cellForRowAtIndexPath method, so you can assign it dataSource and delegate to self
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell", for: indexPath)
return cell
case 1:
if let cell = tableView.dequeueReusableCell(withIdentifier: "ItemTitle", for: indexPath) as? ItemCell {
cell.collectionView?.delegate = self
cell.collectionView?.dataSource = self
return cell
}
...
}
}
And from ViewController you can make performSegue method
Collectionview reload not working when reload from custom tablecell.
I have put a dropdown inside one collectionview cell.this dropdown also not working.
Here is the code:
class HotelAvailableRoomsTVCell: UITableViewCell {
#IBOutlet weak var collectionView: UICollectionView!
//MARK: Life cycle
override func awakeFromNib() {
super.awakeFromNib()
let nib = UINib.init(nibName: "AvailableRoomCVCell", bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: "AvailableRoomCVCell")
collectionView.delegate = self
collectionView.dataSource = self
// Initialization code
}
func initCellWithData(roomJSON:JSON,indexPath:IndexPath,isSingle:Bool) {
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
In viewController:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HotelAvailableRoomsTVCell", for: indexPath) as! HotelAvailableRoomsTVCell
cell.delegate = self
cell.initCellWithData(roomJSON: (json)!, indexPath: indexPath as IndexPath, isSingle: true)
return cell;
}
Screen is:
I have used a tableview with dynamic number of cells as collectionview. this collection view contains a dropdown as shown in image
First of all, do this & check
class HotelAvailableRoomsTVCell: UITableViewCell, UICollectionViewDelegate,UICollectionViewDataSource
You can also do this, (already done by me and its working),
Pass the data by creating var in HotelAvailableRoomsTVCell.
var collectionData : [String : Any] = []
In cellForRow
cell.collectionData = data
In my view controller I want to have two collection views. After trying this, I got a Sigabrt Error and my app crashes. I am predicting that the problem is because I am assigning the datasource of these collection views to self. I can be wrong, here is my code:
In view did load, i set the datasource of the collection views:
#IBOutlet var hashtagCollectionView: UICollectionView!
#IBOutlet var createCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
createCollectionView.dataSource = self
hashtagCollectionView.dataSource = self
}
Then I create an Extension for the UICollectionViewDataSource
extension CategoryViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var returnValue = 0
if collectionView == hashtagCollectionView {
// Return number of hashtags
returnValue = hashtags.count
}
if collectionView == createCollectionView {
// I only want 3 cells in the create collection view
returnValue = 3
}
return returnValue
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var return_cell: UICollectionViewCell
// Place content into hashtag cells
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hashtagCell", for: indexPath) as! TrendingTagsCollectionViewCell
cell.hashtagText = hashtags[indexPath.row]
// Place content in creators cell
let createCell = collectionView.dequeueReusableCell(withReuseIdentifier: "createCell", for: indexPath) as! CreateCollectionViewCell
createCell.text = creators[indexPath.row]
createCell.image = creatorImages[indexPath.row]
// Is this the right logic?
if collectionView == hashtagCollectionView {
return_cell = cell
} else {
return_cell = createCell
}
return return_cell
}
}
This is crashing because your if statement in collectionView(_:cellForItemAt:) doesn't quite cover enough ground.
While you're right that you need to return a different cell based on what collection view is asking, you can't call dequeueReusableCell(withReuseIdentifier:for:) twice with different identifiers like that. Since you ask the same collection view both times, it's very likely that one of the identifiers isn't registered with that collection view.
Instead, you should expand the if to cover just about the entirety of that method:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == hashtagCollectionView {
// Place content into hashtag cells
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hashtagCell", for: indexPath) as! TrendingTagsCollectionViewCell
cell.hashtagText = hashtags[indexPath.row]
return cell
} else if collectionView == createCollectionView {
// Place content in creators cell
let createCell = collectionView.dequeueReusableCell(withReuseIdentifier: "createCell", for: indexPath) as! CreateCollectionViewCell
createCell.text = creators[indexPath.row]
createCell.image = creatorImages[indexPath.row]
return cell
} else {
preconditionFailure("Unknown collection view!")
}
}
That only tries to dequeue a cell once, depending on which collection view is asking, and casts the returned cell to the right class.
N.B. This kind of approach works for awhile, but in the long run, you can get very long UICollectionViewDataSource method implementations, all wrapped up in a series of if statements. It might be worth considering separating out your data sources into separate smaller classes.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hashtagCell", for: indexPath) as? TrendingTagsCollectionViewCell {
cell.hashtagText = hashtags[indexPath.row]
return cell
}
if let createCell = collectionView.dequeueReusableCell(withReuseIdentifier: "createCell", for: indexPath) as? CreateCollectionViewCell {
createCell.text = creators[indexPath.row]
createCell.image = creatorImages[indexPath.row]
return createCell
}
return UICollectionViewCell() // or throw error here
}
I think your code crash with a nil when reuse cell
You should test cellForItemAt like this
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == hashtagCollectionView {
// Place content into hashtag cells
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "hashtagCell", for: indexPath) as! TrendingTagsCollectionViewCell
cell.hashtagText = hashtags[indexPath.row]
return cell
} else {
// Place content in creators cell
let createCell = collectionView.dequeueReusableCell(withReuseIdentifier: "createCell", for: indexPath) as! CreateCollectionViewCell
createCell.text = creators[indexPath.row]
createCell.image = creatorImages[indexPath.row]
return createCell
}
}
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}
}