Create IBAction for CollectionViewCell - ios

I've got a collection view with multiple cells created programically. I want to update a variable to a different value when the user taps a specific cell. So eg: Cell 1 is tapped -> var test = "cell1" , cell2 is tapped var test = "cell2". Usually I'd just create an IBAction by dragging from the storyboard but I'm not sure how to do it in this case.
I'm using Swift 3.1

To add interactivity to UITableViews, UICollectionViews, and other kinds of views which display collections of data, you can't use Storyboard actions, as the content is generated dynamically during runtime, and the Storyboard can only work for static content.
Instead, what you need to do is set your UICollectionView's delegate property to an object that implements the UICollectionViewDelegate protocol. One of the methods defined as part of the protocol is the collectionView(_:didSelectItemAt:) method. This method will get called whenever the user selects (taps) a collection view cell with the IndexPath to that cell as an argument. You can update your variable in that method. Just remember to deselect the cell after handling the tap by using the deselectItem(at:) method on your UICollectionView.

There are UICollectionView delegate that you need to implement. It goes like this
did select item at index path will give index path of the cell that was selected. Using indexpath or any other property of the data source array you are using, you can modify the variable value.
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) {
//check your condition and modify the variable value depending on index path or any other property you are referring to.
}
}

Related

using a Struct to change tableViewCell from TableViewController

In my app's chat feature, I use a UITableView to present chat history.
Cells are subclasses of UITableViewCell. The class receives a Chat object that contains all the info it needs to build the cell.
I have a Firebase listener that fires when the "last message" is changed. It changes a UILabel text to "new Message!" and then a protocol/delegate reloads the table view. Now I need to change the label back to "".
When the user clicks the cell, I use didSelectRowAt to segue to JSQMessagesViewController after preparing for segue. My idea is to use prepare for segue or even didSelectRowAt itself to change a Boolean variable in the UITableViewCell that corresponds to that chat Object. Navigating back to the tableViewController will trigger reloadData.
Each ChatObject has a unique ID that I can access. After firing the listener, I will set this Boolean to one value. After clicking the cell, I will set it to another. the state of the variable will tell the IBOutlet what text to show. In the UITableViewCell class, I use:
var chat: Chat! {
didSet {
self.updateUI()
}
}
}
So in self.updateUI() I make necessary changes, but can I make properties in the UITableViewCell mutable/visible from the UITableViewController?
How can I make properties in the UITableViewCell that are mutable from the UITableViewController
You don't. You make changes in your model and tell the table view to reload its data.
So in self.updateUI() I make necessary changes, but can I make properties in the UITableViewCell mutable from the UITableViewController?
I don't think you're trying to do what you say you are. In the case that you are trying to access the properties of your custom UITableViewCell subclass, you might want to use cellForRowAtIndexPath(). Then cast the result to whatever class name you have for your UITableViewCell subclass.
Example:
If I want to change the 5th row outside of our table view dataSource, I could do something like this.
let fifthIndexPath = IndexPath(row: 5, section: 0)
let thisCell = myTableView.cellForRowAtIndexPath(at indexPath: fifthIndexPath) as! MyCustomTableViewCell
thisCell.property = value
See:
https://developer.apple.com/documentation/uikit/uitableviewdatasource/1614861-tableview

Is there a way to -preload- UICollectionViewCell?

Something that bother me for a long time.
Is there a way to preload UICollectionViewCell ?
something to prepare before loading the data, so the cell will not be create while user is scrolling.
Is there a way to take Full control on WHEN to create the UICollectionViewCell and WHEN to destroy the UICollectionViewCell.
From Apple documentation:
You typically do not create instances of this class yourself. Instead, you register your specific cell subclass (or a nib file containing a configured instance of your class) with the collection view object. When you want a new instance of your cell class, call the dequeueReusableCell(withReuseIdentifier:for:) method of the collection view object to retrieve one.
The cell itself is not a heavy resource, so it makes a little sense to customize its lifetime.
I think that instead of searching for a way to take a control over cell creation, you should ask yourself: why do you want to preload a cell? What kind of heavy resource would you like to preload?
Depending on the answer you can try following optimizations:
If you have complex view hierarchy in your cell, consider refactoring from Autolayout to manual setting frames
If your cell should display results of some complex computations or remote images, you would like to have a separate architecture layer for loading these resources and shouldn't do it in cell class anyway. Use caching when necessary.
You can blackout your screen while you enter into scene and navigate (scroll) to each cell type. When you did scroll each cell you should hide blackout view and present collection view on first cell (top).
It is some kind of workaround. My cells have a lot resources like images, which lag while scrolling collection view.
I can add some actual approach
If you need to preload some data from internet / core data checkout https://developer.apple.com/documentation/uikit/uicollectionviewdatasourceprefetching/prefetching_collection_view_data
tl;dr
first you need your collection view datasource to conform UICollectionViewDataSourcePrefetching in addition to UICollectionViewDataSource protocol
then prefetch your data and store it in cache
func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
// Begin asynchronously fetching data for the requested index paths.
for indexPath in indexPaths {
let model = models[indexPath.row]
asyncFetcher.fetchAsync(model.id)
}
}
and finally feed your cell with your cached data
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Cell.reuseIdentifier, for: indexPath) as? Cell else {
fatalError("Expected `\(Cell.self)` type for reuseIdentifier \(Cell.reuseIdentifier). Check the configuration in Main.storyboard.")
}
let model = models[indexPath.row]
let id = model.id
cell.representedId = id
// Check if the `asyncFetcher` has already fetched data for the specified identifier.
if let fetchedData = asyncFetcher.fetchedData(for: id) {
// The data has already been fetched and cached; use it to configure the cell.
cell.configure(with: fetchedData)
else
... async fetch and configure in dispatch main asyncd
Also u can approach some workaround using delegate methods to handle willDisplay, didEndDisplay events e.g. https://developer.apple.com/documentation/uikit/uicollectionviewdelegate/1618087-collectionview?language=objc

Change variable based on Table View Cell

I need an event, that changes a variable based on which TableViewCell I click. But unlike an action connected to a button, there is no action indicator for table view cells at all. So my question is:
I want to make a TableView that contains items of an array. Based on which item I click, I want to change my variable so that the result on the next ViewController depends on which button you click.
So to make things easier, here is an example what I want the app to look like:
On the first TableViewController I have a list based on an array and on the second ViewController I have a label that shows text based on the variable.
I have a nameArray = ["Mum", "Brother", "Me"] and a weightArray = [140, 160, 120] and a variable weight = 0. The label on the second ViewController tells the var weight. So when you click on "Mum" in the TableView I want the next ViewController to say 140, when I click on "Brother" then 160 and so on...
Until here everything works just fine and I have no problems with anything but changing the var based on what I click.
Long story, short sense:
I want an Action for the TableViewCell that changes the var like in an Action connected to a Button, but there is no Action outlet for Cells at all.
Use this method. Use indexPath.row to find what row number you selected
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var cell : UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
switch cell.labelSubView.text as! String {
case "Mum":
self.weight = weightArray[0]
case "Brother"
self.weight = weightArray[1]
and so on..
..
default:
statements
}
}
Note A better alternative
I also considered a case where you have too many entries in nameArray and switch statement might not be good. In that case you can get the text inside the selected row by cell.labelSubView.text as! String
next you can check if the nameArray contains the cell text and get the index of the name that matches the cell text. Next you can get the required weight at the same index in weightArray. And then do self.weight = weightArray[requiredIndex]
Hope this helps.
Update : My experienced friend #Duncan mentioned down below that switch statement in this case is a bad coding practice . I am not going to delete it because it is a lesson for me and also my fellow programmers who are relatively new to programming. So i have put it in a yellow box, stating that it is not a good code
A better option for this would be :
As Duncan mentions, creating an array of dictionary is a good option
Second option is the option in my answer after my Note
You need to maintain array of dictionaries , those dictionaries have keys like "person", and "weight", then you can easily get weight value after selecting the cell by using table view delegate method UITableViewDelegate's tableView:didSelectRowAtIndexPath:
Create an instance variable in your view controller (a var at the top level after the class definition) for the selected cell.
class MyTableViewController: UIViewController
var selectedRow: Int
override func tableView(tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath)
{
selectedRow = indexPath.row
//invoke a segue if desired
performSegueWithIdentifier("someSegue");
}
override func prepareForSegue(segue: UIStoryboardSegue,
sender: AnyObject?)
{
if segue.identifier == "someSegue"
{
//Cast the destination view controller to the appropriate class
let destVC = DestVCClass(segue.destinationViewController)
destVC.selectedRow = selectedRow
}
}
As Andey says in his answer, it's probably better to create a single array of data objects (dictionaries, structs, or custom data objects). Then when the user taps a cell, instead of passing the index of the selected row to the next view controller, you could pass the whole data object to the destination view controller. Then the destination view controller could extract whatever data it needed. (Weight, in your example.)

How do I access the indexPath.item in my button function?

I have a program that will search a database and populate the collection view. That currently works. Every item has a "follow" button, and when that button is clicked I need it to perform an action, but I need that action to have access to the indexPath.item. The reason why the program is crashing is because the function for the button is hidden in the collection view method, but this is the only way I can gain access to the indexPath.item. How do I fix the crashing and still have access to the indexPath.item?
func followuser(sender: UIButton){
let pointInTable: CGPoint = sender.convertPoint(sender.bounds.origin, toView: self.collectionview)
if var indexPath :NSIndexPath = self.collectionview.indexPathForItemAtPoint(pointInTable){
print(pointInTable)
}
var relation: PFRelation = (PFUser.currentUser()?.relationForKey("Friendship"))!
//relation.addObject(users[indexPath.item])
print(relation)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionview.dequeueReusableCellWithReuseIdentifier("searchcell", forIndexPath: indexPath) as! searchcustomcell
cell.follow.addTarget(self, action: "followuser:", forControlEvents: UIControlEvents.TouchUpInside)
I'm not sure what you mean by indexPath.item. NSIndexPath does not have a property item, so that code can't possibly work unless you've created a category of NSIndexPath.
And I'm not sure where you are getting the value for your indexPath variable.
You have a couple of challenges. The first challenge is to the get the indexPath of the cell that contains the button that was tapped.
One way you do that is to use the UICollectionView method indexPathForItemAtPoint. You'd take your button's bounds and use one of the UIView methods for converting points between coordinate systems to convert the button's origin from it's coordinate system to the collection view's coordinate system. You'd then take that converted coordinate and use it in a call to indexPathForItemAtPoint to get the indexPath that contains the button.
Next challenge: What is it you want to look up by indexPath?
Table views and collection views typically store their model data in either a 1 dimensional array (for a single row of items) or a 2 dimensional array (for a grid of cells.)
You need to take the index path and get either the row or the row and section and use that to index into your model to fetch whatever it is you need to fetch.
However we can't help you with that until you tell us how your collection view is organized and how the model that represents your cell data is stored.

Call UITableViewCell Method from Method in main VC?

I'm trying to do the opposite of what most people on this topic are asking to do. Most people want a button within a table view cell to call a method in their VC / VC table. I already have a protocol doing that.
Problem / Question
What I am trying to add now is the opposite: I need a button press on my main ViewController (which houses my table) to call a method within my CusomTableViewCell class (note: the button pressed on the main VC is not in the table). I have the protocol class created and the function written, but I don't know how to set the CustomCellViewClass as the delegate. When I did the opposite, I inserted "cell.delegate = self" into the cellForRowAtIndexPath method. I've also used prepareForSegue to assign a delegate. But with no segue and now cell-creation-method, I'm lost!
Example of Desired Function
My end goal is that pressing a button that is in the main VC will change the title of a button within the cells. A simple example would be that I have one view with a single table, on button press the table contents switch between two arrays, cars and motorcycles. When the table is showing cars, the cell button titles should all read "Look inside" but when showing the motorcycle button it should read "Look closer".
Code
I've already written the function that I want the cell to execute:
func cellButton_Title_Switch (currentList: String) {
if vcState == "cars" {
cellButton.setTitle("Look inside", forState: UIControlState.Normal)
}
else {
cellButton.setTitle("Look closer", forState: UIControlState.Normal)
}
}
I created the protocol:
protocol delegateToChangeCellBut {
func cellButton_Title_Switch (currentList: String)
}
I have the self.delegate.cellButton_Title_Switch(currentList) within my VC button and the protocol added to my custom cell class declaration. But how do I do that last missing piece in the custom cell class, where I assign the class to the delegate?
My original problem was that my UITableView's cell has buttons and labels, some of which change to match the state of things outside the table, things handled by the mainViewController.
The custom cell is defined by a customCellviewController. All the custom cell buttons and labels have their IBOutlets connected to the customCellviewController. I couldn't figure out how to make an action/change outside the table (in the mainViewController) immediately cause the cell labels and buttons to change.
Note: Protocols tend to work they other way around (a cell action triggers a function in the mainVC). I couldn't figure out how to use a protocol to solve this. Luckily, the solution was much simpler than a protocol.
The Solution!
I wrote the "updateCell" method that would change the labels and buttons and that code now sits in the customCellviewController. Then I called/triggered the "updateCell" function from the mainViewController simply by adding the call into my cellForRowAtIndexPath function. So it looks something like this:
var stateOfPage = "Green"
//Creates the individual cells. If the above function returns 3, this runs 3 times
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//Setup variables
let cellIdentifier = "BasicCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! customCell
cell.updateCell(stateOfPage)
return cell
}
Now the above code/method runs when the table gets built. So to update the cells, have some button tap or other action reload the table data:
tableView.reloadData()
Good luck.

Resources