微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

按下按钮时,在UITableViewCell内找到按钮的indexPath?

下面的代码正确返回单元格:

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,它会崩溃:

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

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

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,然后您只需访问按钮的标签即可找出它所属的行.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐