点击单元格内的图像时如何获取indexPath

How to get indexPath when image inside cell tapped

我想实现的功能是,如果在 tableviewCell 中点击 profileImage,则转到 detailView。我添加了 tapGesture 但我仍然无法弄清楚如何让 indexPath 传递数据。 我这样试过,但应用程序会崩溃。

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "detailSegue" {
            let next: DetailViewController = segue.destination as! DetailViewController
          // pattern1
 let indexPath = tableView.indexPath(for: sender as! CustomTableViewCell)
         // pattern2
        let indexPath = tableView.indexPathForSelectedRow! as NSIndexPath

            next.data = datas[indexPath.row]
        }
    }

我该如何解决这个问题?提前致谢!

If you add UITapGestureRecognizer to an UIImageView then don't forget to set isUserInteractionEnabled property to true.

创建一个变量来存储所选内容 indexPath.row

var selectedCell:Int!

cellForRow 方法中向图像视图添加手势。

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapBtnAction(_:)))
cell.imageView.tag = indexPath.row
cell.imageView.addGestureRecognizer(tapGesture)

在目标方法中执行 segue

func tapBtnAction(_ sender: UITapGestureRecognizer) {
    print("\(sender.view.tag) Tapped")
    self.selectedCell = sender.view.tag
    self.performSegueWithIdentifier("detailSegue", sender: self)
}

prepareforsegue方法中从数组中获取数据。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

   if segue.identifier == "detailSegue" {
      let next: DetailViewController = segue.destination as! DetailViewController
       next.data = datas[self.selectedCell]
   }
}

解决方案 1:使用 touchBegun 方法,确保启用 imageView UserInteraction

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first
      if let cell = touch?.view?.superview?.superview as? YourCellClass {
        let indexPath = yourTablView.indexPath(for: cell)
    //Do whatever you want
    }
}

方案二:可以使用按钮。

@IBAction func onBtnClick(_ sender : UIButton) {
    if let cell = sender.superview?.superview as? UITableViewCell {
        let indexPath = tbl_songsInfo.indexPath(for: cell)
    //Do whatever you want
    }
}

解决方案 3:同上,但使用 sender.tag

@IBAction func onBtnClick(_ sender : UIButton) {
    let data = yourDataArray[sender.tag] 
    //Do whatever you want
}

1: 在cellForRowAtIndexpath方法中设置ImageView的tag,tag等于indexPath.row

imgView.tag = indexPath.row

2:将目标添加到附加在 imageView 上的 tapGuestureRecognizer

3: 在该方法中获取 imageView 的标签

let imgView = sender as! UIImageView
let tag = imgView.tag

4: 相应地获取数据,并推送

let next = self.storyBoard.instatiateViewController(WithIdentifer:"detailVC") 
next.data = datas[tag]
self.navigationController.pushViewController(next)

有多种方法可以实现这一点,但最简单的方法是在 UIImageView 上方添加 UIButton。 并根据 UITableViewCell 的 IndexPath 设置 UIButton 的标签,并添加 UIButton 的点击事件。

cell.btnImage.tag = indexPath.row

当用户尝试点击UIImage时,会点击图片上方的UIButton并触发按钮的click事件,这里可以获取点击的UIButton的索引,与UIImageView相同特定单元格。

@IBAction func BtnClick(_ sender : UIButton) {

     print(sender.tag)//here you will get the IndexPath for that particular UIImageView in Cell.

}

我制作了一个示例项目来演示该解决方案。它工作得很好。看动图!

您可以下载示例项目代码使用link https://drive.google.com/file/d/1zF8Uq2H6eQYyrHU6KqnZu7b5cU_HtZY0/view?usp=sharing

实际上,您必须向您的图像添加一个手势识别器并为此手势附加一个动作。请参见 cellforRowAt 的实现。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

 let cell = tableView.dequeueReusableCell(withIdentifier:"TableViewCellUser") as! TableViewCellUser
 //handle image and its gesture

 cell.imgUser.image = userImagesArray[indexPath.row]
 //enable the interaction so that touch could be captured.
 cell.imgUser.isUserInteractionEnabled = true
 let gesture = UITapGestureRecognizer(target: self, action:  #selector(userImageTapped(gesture:)))
 gesture.numberOfTouchesRequired = 1
 gesture.delegate = self as? UIGestureRecognizerDelegate
 cell.imgUser.tag = indexPath.row
 cell.imgUser.addGestureRecognizer(gesture)
 //handle label
 cell.lblUserName.text = userNames[indexPath.row]
 return cell

}

//用户点击时的动作

guard let indexPathRow = gesture.view?.tag else {
  return
}
print(indexPathRow)
guard indexPathRow >= 0 else {
  print("Array index must be greater than zero. Going to  return")
  return
}
selectedUserImage = userImagesArray[indexPathRow]
selectedUserName = userNames[indexPathRow]
self.performSegue(withIdentifier: "UsersToDetail", sender: self)

您可以从上面提到的 link 下载完整的工作代码。如果发生任何问题,请在评论中告诉我

这个link也会有帮助 [UITapGestureRecognizer tag]: unrecognized selector sent to instance