按下按钮时在 UITableViewCell 中查找按钮的 indexPath?

Find the indexPath of a button inside UITableViewCell when button pressed?(按下按钮时在 UITableViewCell 中查找按钮的 indexPath?)
本文介绍了按下按钮时在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
appearance().setBackgroundImage Not Working On Custom Class(外观().setBackoundImage在自定义类上不起作用)
Show/Hide barButtonItem(显示/隐藏barButtonItem)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)