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


基础教程推荐
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01