swift: how to get the indexpath.row when a button in a cell is tapped?
此链接是点击按钮时的答案,如果无法回答我的问题,我将只使用按钮并将图像放在上面。我只是想知道是否可以通过点击 UIImageView
而不是按钮来实现这一点。我用 UIImageView
而不是 UIButton
尝试了确切的答案,但我得到了这个错误
"fatal error: unexpectedly found nil while unwrapping an Optional value".
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)
}
最佳答案
这可能对你有帮助,
将 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);
}
关于ios - 当点击单元格中的 UIImageView 时如何获取indexpath.row?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35500137/