加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:28:21 所属栏目:百科 来源:网络整理
导读:下面的代码正确返回单元格: func findSuperView(sender:UIButton!) - UITableViewCell { var superView : UIView? = sender.superview var foundSuperView : UITableViewCell! while superView != nil foundSuperView == nil { if let cell = superView as?
下面的代码正确返回单元格:

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的解决方案,它更加强大.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读