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

不羁岁月 提交于 2019-12-20 08:49:29

问题


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.


回答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
}



回答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].




回答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




回答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.




回答5:


I think you were having the same problem I was. I kept getting an error when overriding tableView:didSelectRowAt, and the reason was that I'm used to just calling super.tableView:didSelectRowAt, but in this case we don't want to do that. So just remove the call to the super class method to avoid the run-time error.



来源:https://stackoverflow.com/questions/9703541/fire-a-method-from-a-static-cell-in-a-table-view-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!