Fire a method from a Static Cell in a Table view Controller
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.
Related videos on Youtube
Comments
-
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 over 12 yearsi 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 over 12 yearsif ([indexPath isEqual:[NSIndexPath indexPathForRow:1 inSection:2]]) [self myMethod];
-
Nestor almost 11 yearsI had to change
self.table
toself.tableView
. -
Frank Schmitt over 10 yearsI like @MaxGabriel's answer better because you can reorder the cells without changing your code.
-
CiNN over 8 yearsbut is it optimized ? if it is not a static cell it will create a new cell ?
-
CiNN over 8 yearsmaybe the use of indexPathForCell is best
-
Lasse Bunk about 8 years@CiNN Just for posterity, this will not create a new cell.