I have a collectionView within a tableview and I am trying to access the collection view's indexPath in order to get its contents upon selecting it.
Here is my code:
TableView
//This grabs the indexPath of the collectionView Selected with its contents
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedDeal = dealArray[indexPath.row]
}
ViewController
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let cell = tableView.dequeueReusableCell(withIdentifier: "SpecialPicTableViewCell", for: indexPath) as! SpecialPicTableViewCell
//Defines the selected
let deal = cell.selectedDeal
//Grabs selected information here
dealSelected = deal.title ?? ""
//Then segues
performSegue(withIdentifier: "goToDeal", sender: nil)
tableView.deselectRow(at: indexPath, animated: true)
}
However, the selection does not register with the TableView. Nothing happens as a result.
The only information in the collection view is information you put there. You shouldn't need to get any information out of the collection view cell because you already have it.
The code you posted dequeues (possibly creates) a cell, cleans it up and gets it ready for use (possibly reuse.) That cell that you essentially created will know nothing about the data that is in the cell that was selected.
What you should be doing instead, is referring to the array where you store the deals to display and figuring out what deal is at the selected index path.
Related
I have a UICollectionView that appropriately recognizes taps on its cells in its collectionView(didSelectItemAt: ) delegate method.
However, I then embedded a collection view within the cell itself (so that each cell has its own collection view inside of it), but now the parent cell is not recognizing any taps anymore, I'm assuming because the embedded collection view is eating them up.
Is there some property that needs to be set so that the original (parent) cells register taps again even with their embedded collection views?
This functionality can be confusing, as users are accustomed to "something else" happening when interacting with a control in a table view cell, rather than it selecting (or also selecting) the row itself.
However, if you really want to do that...
One approach is to use a closure in your cell. When you handle didSelectItemAt use the closure to tell the table view controller to select the row.
Note that Apple's docs point out:
Note
Selecting a row programmatically doesn't call the delegate methods tableView(_:willSelectRowAt:) or tableView(_:didSelectRowAt:), nor does it send selectionDidChangeNotification notifications to observers.
So, if you need to execute code when a table view row is selected, you'll need to call that yourself - something like this:
func myTableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("My didSelectRowAt:", indexPath)
}
Using the code in my answer to your previous question...
In SomeTableCell add this closure setup:
public var didSelectClosure: ((UITableViewCell) ->())?
and, still in SomeTableCell:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("collectionView didSelecteItemAt:", indexPath)
print("Calling closure...")
didSelectClosure?(self)
}
Next, in cellForRowAt in the table view controller, set the closure:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "someTableCell", for: indexPath) as! SomeTableCell
cell.rowTitleLabel.text = "Row \(indexPath.row)"
cell.thisData = myData[indexPath.row]
cell.didSelectClosure = { [weak self] c in
guard let self = self,
let idx = tableView.indexPath(for: c)
else { return }
// select the row
tableView.selectRow(at: idx, animated: true, scrollPosition: .none)
// that does not call didSelectRowAt, so call our own func
// if we want something to happen on row selection
self.myTableView(tableView, didSelectRowAt: idx)
}
return cell
}
you can implement UICollectionViewDataSource & UICollectionViewDelegate methods of inner collectionViews inside the cells itself & pass the events with closure to main class with main UICollectionView.
I am doing a screen where there a list o cells with a switch, like an image below;
I have a struct where a save the label of the cell and the switch state value. This struct is loaded at: var source: [StructName] = [] and then source values are attributed to the UITableView cells.
The problem is that when a touch a cell the function: func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) change multiples cells switches states at the same time.
I try to work around the problem by implementing the following function:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
for n in 0..<source.count{ // This loop search for the right cell by looking at the cell label text and the struct where the state of the switch is saved
if cell.label.text! == source[n].Label{
// If the label text is equal to the position where the values is saved (is the same order that the cells are loaded in the UITableView) then a change the state of the switch
let indexLabel = IndexPath(row: n, section: 0)
let cellValues = tableView.cellForRow(at: indexLabel) as! CustomTableViewCell
if cellValues.switchButton.isOn {
cellValues.switchButton.setOn(false, animated: true)
source[n].valor = cellValues.switchButton.isOn
} else {
cellValues.switchButton.setOn(true, animated: true)
source[n].valor = cellValues.switchButton.isOn
}
break
}
}
although is saved the right values to the switch state array(source) the visual state of multiples switches also changes even though the cells where never touch.
How could I change my code to select and change only the touched cell?
You should not store / read the state of anything in a cell.
But first things first:
Why do loop through all the values? You should be able to access the row in the data model directly by indexPath.row
You should only modify the model data, not the cell
You then tell the table view to reload the cell, which will then ask the model for the correct data to be displayed.
I would suggest the following:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let row = indexPath.row
source[row].valor.toggle()
tableView.reloadRows(at:[indexPath], with:.automatic)
}
I'm working on a personal project and I want to make the cells in my UITableView clickable, such that when they are pressed they segue to the next view, and pass information from their cell along with it when they are pressed.
I've attempted to look over other guides and videos that demonstrate how to do this, however they are all outdated. One that stood out to me that seemed to show promise but didn't end up working was in reference to a certain "didSelectRowAt" function, but I could not get this to work.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as!
CandidateTableViewCell
if (indexPath.row >= candidateCells.count){
print("???")
candidateCells.append(cell)
print("Strange error")
}
tableView.delegate = self
cell.CandidateName?.text = candidatesNames[indexPath.item]
cell.CandidatePos?.text = candidatesPositions[indexPath.item]
//cell.candidateButton.tag = indexPath.row
cell.CandidateName.sizeToFit()
cell.CandidatePos.sizeToFit()
print(candidateCells)
print(indexPath.row)
print(candidateCells.count)
print(indexPath.row >= candidateCells.count)
candidateCells[indexPath.item] = cell
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "Segue", sender: Any?.self)
}
What I was expecting to happen was that the cell would become clickable, and when the cell is clicked it would send me to the next page in the app, however when clicked, nothing happens. The cell does not become highlighted, and the segue does not occur. Thank you so much for any and all suggestions!
If you want to pass information to the next cell, I usually avoid using a Segue, and setup the ViewController with a reuse identifier. By doing this, you can pass information easier. For instance
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "YOURRESUEIDENTIFIER") as! YOURVIEWCONTROLLERCLASS
vc.infoToPass = cellData[indexPath.row]
DispatchQueue.main.async {
self.navigationController?.pushViewController(vc, animated: true)
}
}
Your other option would be to implement the shouldPerformSegueWithIdentifier() method in order to set the data properly. You would click your cell, which calls the performSegue function, which would call the shouldPerformSegueWithIdentifier where you can set the data and return true
I have a image inside my tableview cells that turns black when the cell is selected as well as the default cell turning gray. Problem is when I scroll down the screen and scroll up again the images are turn back as though they are not selected being image "cellSelected". So, after scrolling selected cells should have the image "cellSelected" yet they have "cellNotSelected". How can I make sure my app remembers the selected cells images?
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! CustomerSelectsBusinessesCell
cell.selectedCell.image = UIImage(named: "cellSelected")
updateCount()
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! CustomerSelectsBusinessesCell
cell.selectedCell.image = UIImage(named: "cellNotSelected")
updateCount()
}
You need to save the change of state in your data model somewhere, and then edit your data source methods (specifically cellForRowAtindexPath) to show the cell in its new selected state.
This is true of any change you make to a cell. If the cell scrolls off-screen, it gets recycled and any customizations you've made to it's views will not longer be associated with that indexPath any more. So when the user takes action on a cell, you always need to record the information in your data model.
My collectionView displays images of characters that have been added as a favorite. This is persisted in Core Data.
On a detail view controller, the user clicks the favorite button which adds the character to favorites. When it is clicked again, the figure is removed.
The problem is the images in the collection view are not updated without closing the app and re-running. I tried using:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.favoriteCollectionView.reloadData()
}
But this was unsuccessful. How can I get the collection view to update?
UPDATE: Here is all that is in the cellForItemAt function.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ownedCell", for: indexPath) as! OwnedCollectionViewCell
cell.ownedFigImage.sd_setImage(with: URL(string: favFigArray[indexPath.row]))
return cell
}