按下按钮时在 UITableViewCell 中查找按钮的 indexPath? [英] Find the indexPath of a button inside UITableViewCell when button pressed?

查看:13
本文介绍了按下按钮时在 UITableViewCell 中查找按钮的 indexPath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码正确返回单元格:

The code below correctly returns the cell:

func findSuperView(sender:UIButton!) -> UITableViewCell { 
    var superView : UIView? = sender.superview 
    var foundSuperView : UITableViewCell! 

    while superView != nil && foundSuperView == nil { 
        if let cell = superView as? UITableViewCell { 
            foundSuperView = cell 
            break 
        } 
        else { 
            superView = superView?.superview 
        } 
    } 
    return foundSuperView 
}

但在 tableview 中查找 indexpath 时会崩溃:

But for finding indexpath in tableview it crashes:

var indexPath : NSIndexPath = self.table .indexPathForCell(findSuperView(sender))!
println("Section (indexPath)")

我尝试了另一种方法,但没有成功:

And I tried another way, but it was not successful:

var button : UIButton = sender as UIButton; 
var touch: UITouch = events .allTouches()?.anyObject() as UITouch 
var location : CGPoint = touch.locationInView(self.table) 
var indexPath : NSIndexPath = self.table.indexPathForRowAtPoint(location)!

推荐答案

我不知道是否有一个简单的方法来做到这一点.(其实有.看看@mustafa的第二个解决方案.)一种解决方法是在cellForRowAtIndexPath中将按钮的标签设置为indexPath.row, 然后你就可以访问按钮的标签来找出它属于哪一行.

I don't know if there is an easy a way to do this. ( Actually there is. Look at @mustafa's second solution.) A workaround is to set the button's tag to indexPath.row in cellForRowAtIndexPath, then you can just access the button's tag to find out which row it belongs to.

警告:此解决方法很脆弱.如果您允许从表中添加或删除行而不调用 tableView.reloadData(),它将无法正常工作.看看@mustafa 的解决方案,它更强大.

Warning: This workaround is fragile. It won't work correctly if you allow rows to be added or deleted from your table without then calling tableView.reloadData(). Look at @mustafa's solution which is much more robust.

这篇关于按下按钮时在 UITableViewCell 中查找按钮的 indexPath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆