Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

ios - How to access index path of button in a custom TableViewCell?

I have created a custom TableViewCell and currently have a button placed in the cell. When the button is pressed, In the tableviewcell.swift file, IBAction func gets executed. I cannot figure out how to determine the index path of the cell that the button is in that is pressed. I was trying to use the following

    @IBAction func employeeAtLunch(sender: AnyObject) {

    let indexPath = (self.superview as! UITableView).indexPathForCell(self)
    println("indexPath?.row")
}

but I get the following error on click: Could not cast value of type 'UITableViewWrapperView' to 'UITableView'

Any help on how to access the index path of the cell?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are just assuming that the cell's immediate superview is the table view - wrongly. There is no particular reason why that should be so (and indeed it is not). Work with fewer assumptions! You need to keep walking up the superview chain until you do reach the table, like this:

var v : UIView = self
do { v = v.superview! } while !(v is UITableView)

Now v is the table view, and you can proceed to work out what row this is.

What I would actually do, however, is work my up, not from the cell to the table, but from the button to the cell. The technique is exactly the same:

var v : UIView = sender as! UIView
do { v = v.superview! } while !(v is UITableViewCell)

Do that the button's action method, where sender is the button. If the target of the action method is the table view controller, it has access to the table, and the problem is solved.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...