Fire a method from a Static Cell in a Table view Controller

17,487

Solution 1

In the viewController add:

@property (nonatomic, weak) IBOutlet UITableViewCell *theStaticCell;  

Connect that outlet to the cell in the storyboard.

Now in tableView:didSelectRowAtIndexPath method:

UITableViewCell *theCellClicked = [self.tableView cellForRowAtIndexPath:indexPath];
if (theCellClicked == theStaticCell) {
    //Do stuff
}

Solution 2

With static cells, you can still implement - tableView:didSelectRowAtIndexPath: and check the indexPath. One approach, is that you define the particular indexPath with #define, and check to see whether the seleted row is at that indexPath, and if yes, call [self myMethod].

Solution 3

Here is my take when mixing static and dynamic cells,

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
                    if let staticIndexPath = tableView.indexPathForCell(self.staticCell) where staticIndexPath == indexPath {
// ADD CODE HERE 
                }
        }

this avoids creating a new cell. We all are used to create the cell and configure it in cellForRowAtIndexPath

Solution 4

Following CiNN answer, this is the Swift 3 version that solves the issue.

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let staticIndexPath = tableView.indexPath(for: OUTLET_TO_YOUR_CELL), staticIndexPath == indexPath {
        // ADD CODE HERE
    }
}

this approach allow to not necessary implement cellForRow method, specially if you are using static cells on storyboard.

Share:
17,487

Related videos on Youtube

carbonr
Author by

carbonr

Developer

Updated on June 07, 2022

Comments

  • carbonr
    carbonr about 2 years

    In my code i have a table with static cell inside storyboards. I'm trying to fire a method upon clicking the last static cell.

    What should i write in the code to make this happen. How can i refer static cells inside the code without firing error.

  • carbonr
    carbonr over 12 years
    i tried that, when call indexPath.row it throws a error back at me during runtime. How can i check the 3rd section 2nd row?
  • Sierra Alpha
    Sierra Alpha over 12 years
    if ([indexPath isEqual:[NSIndexPath indexPathForRow:1 inSection:2]]) [self myMethod];
  • Nestor
    Nestor almost 11 years
    I had to change self.table to self.tableView.
  • Frank Schmitt
    Frank Schmitt over 10 years
    I like @MaxGabriel's answer better because you can reorder the cells without changing your code.
  • CiNN
    CiNN over 8 years
    but is it optimized ? if it is not a static cell it will create a new cell ?
  • CiNN
    CiNN over 8 years
    maybe the use of indexPathForCell is best
  • Lasse Bunk
    Lasse Bunk about 8 years
    @CiNN Just for posterity, this will not create a new cell.