Tom el Safadi
Tom el Safadi

Reputation: 6746

Get indexpath outside of any tableView function

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?

Upvotes: 1

Views: 1888

Answers (1)

SnowMax
SnowMax

Reputation: 611

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]
    }
}

Upvotes: 1

Related Questions