Get indexpath outside of any tableView function - ios

Maybe my question is very simple and I am just too stupid to get it.
My problem is that I want to access the indexPath outside of
overide func tableView(...)
So I am in my TableView Class and have a separate class like:
func setColor()
{
...
}
Inside this class I want to access the indexPath. How can I do this?

The indexPath is an object, which is created and passed to the UITabelViewDelegate or UITableViewDataSource methods. It lets you indicate which cell is loaded/tapped etc.
So you will not be able to access this object from outside. If you want to change something of a cell e.g. the backgroundColor you should store the color in a property, change this property and force a redraw. In the delegate method, which creates the cells use this property to set the color.
Here is some sample code.
ViewController
class TestTableViewController: UIViewController, UITableViewDelegate {
// Store array of color
var backColors = [UIColor.redColor(), UIColor.greenColor()]
// Method which changes color
func setColor(row: Int, color: UIColor) {
backColors[row] = color
}
// Override draw
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Create your cell
// ...
// Set color
cell.backgroundColor = backColors[indexPath.row]
}
}

Related

iOS (Swift): Collection View indexPath(for: cell) is nil for non visible cell

I have a UIViewController that populates a UICollectionView with an array of type Object:
class MyViewController: UIViewController {
let objects: [Object]!
weak var collectionView: UICollectionView!
func object(for cell: MyCell) {
guard let indexPath = self.collectionView.indexPath(for: cell) else { fatalError("No cell at index path") }
}
}
The collectionView cells are represented by:
class MyCell: UICollectionViewCell {
weak var delegate: MyCellDelegate?
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)
let obj = self.delegate?.object(for: self)
// configure various subviews with obj ...
}
}
which has a delegate that talks to MyViewController to get the Object instance that is representing:
protocol MyCellDelegate: class {
func object(for cell: MyCell) -> Object
}
This works fine when I scroll down between cells however, it crashes at guard let indexPath = self.collectionView.indexPath(for: cell) ... for cells that are off the screen when the apply(_ layoutAttributes: UICollectionViewLayoutAttributes) method is called.
Is there a way to fix this? The cells need to know which instance of Object they are representing so that the view controller can tweak the model.
Thanks a lot for any help!
Always assume that if a cell is offscreen, then the collection view has already recycled it. The collection view constantly does this to keep memory usage low and performance high.
To perform some action offscreen, what I often do is hold a separate object (view model, in MVVM) that a visible cell can attach to. This object is owned and retained by my objects and is never recycled. If I need to do any offscreen action, this object does it.
The cell’s only jobs are:
to display data and
receive user input
Both of those require it to be visible.
When I create cells, I use prepareForReuse to detach it from the previous view model and do necessary clean up before attaching the cell to the next one.
Alternate Solution
If all you need is the index path to get your special object, you could simply use the index path from the layout attributes.
protocol MyCellDelegate: class {
func object(for indexPath: IndexPath) -> Object
}
class MyCell: UICollectionViewCell {
weak var delegate: MyCellDelegate?
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)
let obj = self.delegate?.object(for: layoutAttributes.indexPath)
// configure various subviews with obj ...
}
}

Delegate Method to UItableViewCell Swift

I have a Social Network Feed in form UItableView which has a cell. Now each cell has an image that animates when an even is triggered. Now, This event is in form of a string, will be triggered at every cell. the options for the event are defined in another class(of type NSObject).
My issue:
I constructed a protocol delegate method in table view, which will be called whenever the event is triggered for each cell. Then, I define this function in UITableViewCell Class, since my the image will be animating on that.
All is working well but I am unable to figure out how to assign the delegate of TableView class to cell class. What I mean is, how can I use UITableView.delegate = self in cellView class. I have tried using a static variable, but it doesn't work.
I have been playing around the protocols for a while now but really unable to figure out a solution to this.
I hope I am clear. If not, I will provide with an example in the comments. I am sorry, This is a confidential project and I cant reveal all details.
If I understand you correctly, you are trying to make each of your cells conform to a protocol that belongs to their UITableView? If this is the case then this cannot be done. The Delegation design pattern is a one to one relationship, i.e only one of your UITableViewCells would be able to conform to the UITableView's delegate.
Delegation is a simple and powerful pattern in which one object in a program acts on behalf of, or in coordination with, another object. The delegating object keeps a reference to the other object—the delegate—and at the appropriate time sends a message to it. The message informs the delegate of an event that the delegating object is about to handle or has just handled. The delegate may respond to the message by updating the appearance or state of itself or other objects in the application, and in some cases it can return a value that affects how an impending event is handled. The main value of delegation is that it allows you to easily customize the behavior of several objects in one central object.
Quote from the Apple Docs
I would suggest that your UITableViewCell should call a block (Objective-C) or a closure (Swift) whenever your specified event is triggered to achieve what you are looking for. Set up this closure in your tableView:cellForRowAtIndexPath function.
EXAMPLE
TableViewController
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "MyTableViewCellID", for: indexPath) as! MyTableViewCell
cell.eventClosure = {
//Do something once the event has been triggered.
}
return cell
}
TableViewCell
func eventTriggered()
{
//Call the closure now we have a triggered event.
eventClosure()
}
If I correctly understood your question, maybe this could help:
class ViewController: UIViewController, YourCustomTableDelegate {
#IBOutlet weak var tableView: YourCustomTableView!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.customTableDelegate = self
}
// table delegate method
func shouldAnimateCell(at indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.animate(...)
}
}
}
Try something like this:
Define your delegate protocol:
protocol CustomCellDelegate: class {
func animationStarted()
func animationFinished()
}
Define your CustomCell. Extremely important to define a weak delegate reference, so your classes won't retain each other.
class CustomCell: UITableViewCell {
// Don't unwrap in case the cell is enqueued!
weak var delegate: CustomCellDelegate?
/* Some initialization of the cell */
func performAnimation() {
delegate?.animationStarted()
UIView.animate(withDuration: 0.5, animations: {
/* Do some cool animation */
}) { finished in
self.delegate?.animationFinished()
}
}
}
Define your view controller. assign delegate inside tableView:cellForRowAt.
class ViewController: UITableViewDelegate, UITableViewDataSource {
/* Some view controller customization */
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: CustomCell.self)) as? CustomCell
cell.delegate = self
cell.performAnimation()
return cell
}
}

Swift: How to access a mutable array of strings from one UIViewController to a TableView cell file

I have one view controller named TableViewController and another customised cell called feed.swift
The cells are getting reused properly and I have put tags on various buttons as I wan't to know what button of what feed is pressed on.
In my cellForRowAtIndexPath I'm populating my username with json that I have parsed. It looks like this
cell.username.text = username[indexPath.row]
output-> ["andre gomes", "renato sanchez", "renato sanchez"]
Then I have tagged my username button like this
cell.usernamePress.tag = indexPath.row
This is going on in my TableViewController
In my feed.swift I'm checking if a button is pressed and printing out the tag assigned to that button
#IBAction func usernameBut(sender: AnyObject) {
print(usernamePress.tag)
}
output-> 2
Now I need to access the username array of TableViewController in feed.swift and do something like username[usernamePress.tag]
I tried making a global.swift file but I'm not able to configure it for an array of strings.
import Foundation
class Main {
var name:String
init(name:String) {
self.name = name
}
}
var mainInstance = Main(name: "hello")
Even after doing this I tried printing mainInstance.name and it returned hello even after changing it. I want a solution where the array of strings holds the values I set in TableViewController and I can be able to use them in feed.swift
Any suggestions would be welcome! I'm sorry if there are any similar question regarding this but I'm not able to figure out how to use it for a mutable array of strings
I suggest you don't use the array directly in your FeedCell but instead return the press-event back to your TableViewController where you handle the event. According to the MVC Scheme, which is the one Apple requests you to use (checkout Apples documentation), all your data-manipulation should happen in the Controller, which then prepares the Views using this data. It is not the View that is in charge to display the right values.
To solve your problem I would choose to pass back the press-event via the delegation-pattern, e.g. you create a FeedCellDelegate protocol that defines a function to be called when the button is pressed:
protocol FeedCellDelegate {
func feedCell(didPressButton button: UIButton, inCell cell: FeedCell)
}
Inside your FeedCell you then add a delegate property, which is informed about the event by the View:
class FeedCell {
var delegate: FeedCellDelegate?
...
#IBAction func pressedUsernameButton(sender: UIButton) {
delegate?.feedCell(didPressButton: sender, inCell: self)
}
}
If your TableViewController then conforms to the just defined protocol (implements the method defined in there) and you assign the ViewController as the View's delegate, you can handle the logic in the Controller:
class TableViewController: UITableViewController, FeedCellDelegate {
...
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("FeedCell", forIndexPath: indexPath) as! FeedCell
cell.delegate = self
// Further setup
return cell
}
func feedCell(didPressButton button: UIButton, inCell cell: FeedCell) {
guard let indexPath = tableView.indexPathForCell(cell) else { return }
// Do your event-handling
switch (button.tag) {
case 2: print("Is username button")
default: print("Press not handled")
}
}
}
As you might recognize I changed your class name. A Feed sounds more like a Model-class whereas FeedCell implies its role to display data. It makes a programmer's life way easier if you choose self-explaining names for your classes and variables, so feel free to adapt that. :)
you should add a weak array property to the tableViewCell:
weak var userNameArray:[String]?
Then in your tableViewController pass the username array into the cell:
fun tableView(tableView:UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// create the cell, then...
if let array = self.username {
cell.userNameArray = array
}
}
Then you can use the array in the cell itself to populate its fields handle button taps, etc.

Notify UITableViewController when cell is programmatically selected

My table view allows multiple cell selection, where each cell sets itself as selected when a button inside the cell has been clicked (similar to what the gmail app does, see picture below). I am looking for a way to let the UITableViewController know that cells have been selected or deselected, in order to manually change the UINavigationItem. I was hoping there is a way to do this by using the delegate methods, but I cannot seem to find one. didSelectRowAtIndexPath is handling clicks on the cell itself, and should not affect the cell's selected state.
The most straight forward way to do this would be to create our own delegate protocol for your cell, that your UITableViewController would adopt. When you dequeue your cell, you would also set a delegate property on the cell to the UITableViewController instance. Then the cell can invoke the methods in your protocol to inform the UITableViewController of actions that are occurring and it can update other state as necessary. Here's some example code to give the idea (note that I did not run this by the compiler, so there may be typos):
protocol ArticleCellDelegate {
func articleCellDidBecomeSelected(articleCell: ArticleCell)
func articleCellDidBecomeUnselected(articleCell: ArticleCell)
}
class ArticleCell: UICollectionViewCell {
#IBAction private func select(sender: AnyObject) {
articleSelected = !articleSelected
// Other work
if articleSelected {
delegate?.articleCellDidBecomeSelected(self)
}
else {
delegate?.articleCellDidBecomeUnselected(self)
}
}
var articleSelected = false
weak var delegate: ArticleCellDelegate?
}
class ArticleTableViewController: UITableViewController, ArticleCellDelegate {
func articleCellDidBecomeSelected(articleCell: ArticleCell) {
// Update state as appropriate
}
func articleCellDidBecomeUnselected(articleCell: ArticleCell) {
// Update state as appropriate
}
// Other methods ...
override tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueCellWithIdentifier("ArticleCell", forIndexPath: indexPath) as! ArticleCell
cell.delegate = self
// Other configuration
return cell
}
}
I would have a function like 'cellButtomDidSelect' in the view controller and in 'cellForRowAtIndexPath', set target-action to the above mentioned function

Swift: How can I bind an NSIndexPath to a addTarget

I have a UISwitch in each of my dynamically created rows of which I want to bind an NSIndexPath to an addTarget selector.
I had considered allowing the user to tap the row to toggle the switch, but from a UX perspective it makes more sense to have the switch handle this method, therefore using didSelectRowAtIndexPath is not an appropriate solution.
When my cell is created I currently bind a selector like this:
// Create listener for each switch
prefCell.subscribed?.addTarget(self,
action: "switchFlipped:",
forControlEvents: UIControlEvents.ValueChanged)
Which calls the corresponding method:
func switchFlipped(flipSwitch: UISwitch, indexPath: NSIndexPath) {}
Obviously this throws an error because NSIndexPath isn't a valid reference, as I believe it will only send the buttons reference. Is there any way I can bind the index path? If not, is there any way to get the current cell from the context of the UISwitch?
The target-action pattern does not allow arbitrary selectors. You can have f(sender:) and f(sender:event:). Both won't help you. But you can use code to figure out the indexPath in the function.
Code should be self explanatory:
func switchFlipped(flipSwitch: UISwitch) {
let switchOriginInTableView = flipSwitch.convertPoint(CGPointZero, toView: tableView)
if let indexPath = tableView.indexPathForRowAtPoint(switchOriginInTableView) {
println("flipped switched at \(indexPath)")
}
else {
// this should not happen
}
}
This should be the a good solution, not depending on a point. You call the superviews of the Switch and therefore calculate the index path of the cell.
func switchTapped(sender: UISwitch) -> NSIndexPath {
let cell = sender.superview!.superview! as UITableViewCell
return tableView.indexPathForCell(cell)!
}
This reliably works, that's why you can simply unwrap any optionals.
You can try 3 approaches, as you see fit.
Create a custom UISwitch class and add an NSIndexPath property to it. When you receive notification, type cast to your custom class and access the NSIndexPath.
Create a custom UITableViewCell class and save NSIndexPath to it. When you get notified of UISwitch, get its superviews and see which one is your customUITableViewCell instance and get the property.
If you only have one section, it means all you need to worry about are rows. Set the UISwitch tag as the row number and access it when switch is flipped.
The Most Tech-Savy Solution Use Extensions of Swift.
Extensions add new functionality to an existing class, structure, or enumeration type. This includes the ability to extend types for which you do not have access to the original source code
Apple Docs
Use delegation.
Your switch's target action should be a method in your custom UITableViewCell. That custom tableviewcell should declare a protocol and the tableview should be it's delegate. Then your tableviewcell should call its delegate method from within the switch's target function.
The delegate method for your tableviewcell should have a parameter in which the cell passes self. Then in your tableviewcontroller delegate implementation you can use indexPathForCell:
UPDATE:
Here is the apple doc for swift protocols and delegates:
https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html
Simply put, you need to define a protocol
protocol CustomUITableViewCellDelegate {
func tableViewCellSubscribed(cell: myCustomUITableViewCell) -> Void
}
then you make your tableviewcontroller class conform to that protocol like this:
class myTableViewController: UITableViewController, CustomUITableViewCellDelegate {
func tableViewCellSubscribed(cell: myCustomUITableViewCell) -> Void {
//this is where you handle whatever operations you want to do regarding the switch being valuechanged
}
// class definition goes here
}
Then your custom UITableViewCell class should have a delegate property like this:
class myCustomUITableViewCell : UITableViewCell {
var delegate : CustomUITableViewCellDelegate?
//class definition goes here
}
Finally, set the cell's delegate in tableView:cellForRowAtIndexPath: and you're good to go. You just need to call your tableViewCellSubscribed: delegate function from within the target method of your switch action.
I've used this approach in many projects, you can just add a callback to your custom cell, each time your switch changes, you can run this callback and catch it inside your table datasource implementation, below a dirt and simple example.
1. Create a UITableViewCell custom class
// An example of custom UITableViewCell class
class CustomCell:UITableViewCell {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var onSwitchChange:() -> Void?
}
class TableDataSource:UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomCell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as CustomCell
cell.onSwitchChange = {
NSLog("Table: \(tableView) Cell:\(cell) Index Path: \(indexPath)")
}
}
}
Acctually,Apple has already provide API to get the indexPath.
Simply like this (in Objective-C)
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
Far easier, you can use the tag variable for this :
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
cell.mySwitch.tag = indexPath.item
cell.mySwitch.addTarget(self, action: #selector(switchChanged), for: UIControlEvents.valueChanged)
...
}
func switchChanged(mySwitch: UISwitch) {
let indexPathItem = mySwitch.tag
...
}
From official doc :
var tag: Int { get set }
An integer that you can use to identify view objects in your
application.
The default value is 0. You can set the value of this tag
and use that value to identify the view later.

Resources