swift: how to get the indexpath.row when a button in a cell is tapped?
此链接是点击按钮时的答案,如果我的问题无法解决,我只需使用按钮并将图像放在上面即可。我只是想知道是否可以通过点击UIImageView
而不是按钮来实现这一点。我使用UIImageView
而不是UIButton
尝试了确切的答案,我收到了此错误
"致命错误:在打开一个可选值"时意外发现nil。
cell.imagePosted
是UIImageView
let tapGR = UITapGestureRecognizer(target: self,action:Selector("imageTapped:"))
cell.imagePosted.userInteractionEnabled = true
cell.imagePosted.addGestureRecognizer(tapGR);
func imageTapped(img: AnyObject)
{
if let imgView = img as? UIImageView {
if let superView = imgView.superview {
if let cell = superView.superview as? CellCustom {
indexPath2 = self.tableView.indexPathForCell(cell)
}
}
}
print(indexPath2.row)
}
答案 0 :(得分:1)
这可能会对你有帮助,
向UITapGestureRecognizer
添加UIImageView
您可以将indexpath.row
存储在UIImageView
的代码属性中,并在UITapGestureRecognizer
事件
例如(Objective-C):
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)];
tap.cancelsTouchesInView = YES;
tap.numberOfTapsRequired = 1;
[cell.imageView addGestureRecognizer:tap];
cell.imageView.tag = indexPath.row;
并获取indexpath.row
-(void)handleImageTap:(UITapGestureRecognizer *)gestureRecognizer{
UIView* view = gestureRecognizer.view;
CGPoint loc = [gestureRecognizer locationInView:view];
NSInteger indexpath = [view hitTest:loc withEvent:nil].tag;
NSLog(@"%ld",(long)indexpath);
}
答案 1 :(得分:0)
您可以使用单元格中的imageViewInCellTapped(cell:YourCellType)
和委托属性等方法创建协议。在cellForRowAtIndexPath
中,将控制器设置为每个单元的委托,并从协议中实现该方法。当您的单元格中出现某些事情(如按钮或图像被点击)时,您可以调用delegate?.imageViewInCellTapped(self)
其中self是单元格,然后在控制器中实现此方法,您可以使用tableView的indexPathForCell
方法获取索引。
答案 2 :(得分:0)
如果有人感兴趣的话,这里是Madan的代码:
func imageTapped(gestureRecognizer: UITapGestureRecognizer) {
var view: UIView!
var loc: CGPoint!
view = gestureRecognizer.view
loc = gestureRecognizer.locationInView(view)
var indexPath: NSInteger!
indexPath = (view.hitTest(loc, withEvent: nil)?.tag)!
print(indexPath)
}
答案 3 :(得分:0)
希望此代码有助于获取tapped cell swift 3的索引路径:
func nameTapped(_ sender:UITapGestureRecognizer)
{
var pointVAlue = CGPoint()
pointVAlue = sender.location(in: infoTable)
var indexPath = IndexPath()
indexPath = infoTable.indexPathForRow(at: pointVAlue)!
print(indexPath.row)
/* if indexPath != nil {
let userEnt = ratingArray.object(at: indexPath.row)as! RateEntity
let detailVc = AssociateDetailViewController()
if ((userEnt.userId as String).isEmpty == false )
{
detailVc.m_otherUserId = userEnt.userId as String
self.navController!.pushViewController(detailVc, animated: true)
}
}*/
}