点击UITableView单元格内的图像

时间:2021-12-19 21:08:35

I have two images inside one cell of uitableview, these images shows to images from an external server and each tag of them has an id of item which this image represent, I need if I clicked on this image move user to new view controller which show details of this item, I force a problem, where user need to double click to show details instead of one click, the following my code:

uitableview我有两个图像在一个细胞,这些图像显示图像从外部服务器,每个标签都有一个id项这个形象代表,我需要如果我点击这个图片移动用户的新视图控制器显示这个项目的细节,我强迫一个问题,用户需要双击显示细节,而不是一个点击,以下我的代码:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = self.tableView.cellForRow(at: indexPath as IndexPath) as! prodctCell
        Id1stMove =  cell.image1st.tag
        let tapGesture = UITapGestureRecognizer (target: self, action: #selector(ItemsController.imgTap))
        cell.image1st.addGestureRecognizer(tapGesture)
        cell.image1st.isUserInteractionEnabled = true

        let cell1 = self.tableView.cellForRow(at: indexPath as IndexPath) as! prodctCell
        Id2ndMove =  cell1.image2nd.tag
        let tapGesture1 = UITapGestureRecognizer (target: self, action: #selector(ItemsController.imgTap1))
        cell1.image2nd.addGestureRecognizer(tapGesture1)
    }


func imgTap()
    {
        let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "testViewController") as? testViewController
            let navController = UINavigationController(rootViewController: secondViewController!)
            navController.setViewControllers([secondViewController!], animated:true)
            self.revealViewController().setFront(navController, animated: true)
            revealViewController().pushFrontViewController(navController, animated: true)
        secondViewController?.movmentId = Id1stMove
        updateCount(itemId: Id1stMove)

    }

4 个解决方案

#1


1  

You need to execute this code in cellForRowAt indexPath instead did select.

您需要在cellForRowAt indexPath中执行此代码,而不是选择。

As you said you want to use image id from the tag value I suggest below change in addition of adding code in cellForRowAt indexPath:

正如您说过的,您想要从标签值中使用图像id,我建议在cellForRowAt indexPath中添加代码的更改如下:

Change tapGesture code as below:

更改tapGesture code如下:

let tapGesture = UITapGestureRecognizer (target: self, action: #selector(imgTap(tapGesture:)))

And imgTap function:

和imgTap功能:

 func imgTap(tapGesture: UITapGestureRecognizer) {
        let imgView = tapGesture.view as! UIImageView
        let idToMove = imgView.tag
       //Do further execution where you need idToMove

    }

#2


2  

Yesterday itself I created sample and tried.I got the solution.But I could not post my answer immediately as I had some work.

昨天我自己制作了样品并尝试了。我得到了解决方案。但是我不能马上给出我的答案,因为我还有一些工作要做。

Now I will give you my answer.I don't expect reputation for my below answer.

现在我给你我的答案。我不指望我下面的回答有什么好名声。

When you click or tap the image first time,it navigates.

当你第一次点击或点击图像时,它会导航。

You don't need to add TapGestureRecognizer for imageView in didSelectRowAt method.You need to add TapGestureRecognizer for image View in cellForRowAt method.

在didSelectRowAt方法中,不需要为imageView添加TapGestureRecognizer。在cellForRowAt方法中,需要为图像视图添加TapGestureRecognizer。

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    let mobiles: [String] = ["iPhone", "Android"]
    let images: [String] = ["iPhone.png", "android.png"]
    @IBOutlet var tableViewImageTapping: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // number of rows in table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.mobiles.count
    }

    // create a cell for each table view row
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
        if (cell == nil) {
            cell = UITableViewCell(style:UITableViewCellStyle.default, reuseIdentifier:"cell")
        }
        cell?.textLabel?.text = self.mobiles[indexPath.row]
        let strImageName = images[indexPath.row]
        cell?.imageView?.image = UIImage(named: strImageName)
        cell?.imageView?.tag = indexPath.row
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
        tapGestureRecognizer.numberOfTapsRequired = 1
        cell?.imageView?.isUserInteractionEnabled = true
        cell?.imageView?.addGestureRecognizer(tapGestureRecognizer)
        return cell!
    }

    // method to run when table view cell is selected
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped table view cell index is \(indexPath.row).")
    }

    // method to run when imageview is tapped
    func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
    {
        let imgView = tapGestureRecognizer.view as! UIImageView
        print("your taped image view tag is : \(imgView.tag)")
        if (imgView.tag == 0) //Give your image View tag
        {
            //navigate to next view
        }
        else{

        }
    }
} 

Output Screenshot

输出屏幕截图

点击UITableView单元格内的图像

Printed results are

打印结果

When you click the first image in first click

当您单击第一个图像时,第一次单击

点击UITableView单元格内的图像

Then when you click the second image in first click

然后,当你点击第二个图像,在第一次点击

点击UITableView单元格内的图像

#3


0  

You are assigning the gesture recognizers in the "did select row at index path" method, this means that the user must select (tap) a cell for the gesture recognizers to be assigned to the images, and then the user must tap the image for those recognizers to react by calling "imgTap()", those are the two taps.

你分配的手势识别器来“选择行索引路径”方法,这意味着用户必须选择(tap)细胞的手势识别器来分配给图像,然后用户必须点击图像识别器的反应通过调用“imgTap()这是两个龙头。

What you should do instead is assign the gesture recognizers in the "cell for row at index path" method, so when you create each cell you also create the gesture recognizers, that way when the user taps an image for the first time the tap is recognized and "imgTap()" is called.

你应该做的是分配的手势识别器“细胞的行索引路径”的方法,所以当你创建每个细胞也创建手势识别器,这样当用户首次利用图像水龙头是公认的“imgTap()”。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! CustomCell

    // Configure the cell...

    let tapGesture1 = UITapGestureRecognizer (target: self, action: #selector(ItemsController.imgTap))
    cell.image1st.addGestureRecognizer(tapGesture1)
    let tapGesture2 = UITapGestureRecognizer (target: self, action: #selector(ItemsController.imgTap))
    cell.image2nd.addGestureRecognizer(tapGesture2)

    return cell
}

I also recommend changing the code a little so you can call "imgTap()" with a parameter (the id of what was tapped), instead of having 2 methods "imgTap()" and "imgTap1()".

我还建议稍微修改一下代码,以便您可以使用参数(被选中的内容的id)调用“imgTap()”,而不是使用两个方法“imgTap()”和“imgTap1()”。

#4


0  

  1. Please don't use force unwrap as! prodctCell
  2. 请不要使用强制打开包装!prodctCell
  3. Please use name swift naming conventions
  4. 请使用名称swift命名约定
  5. Don't use .tag cell is usually reused it might break in some edge cases
  6. 不要使用。标记单元格通常在某些边界情况下被重用。

Now back to your question, you already have a custom cell that holds the image. you have several possibilities

现在回到您的问题,您已经有了一个保存映像的自定义单元格。你有几个可能性

  1. Add the gesture recogniser to the imageView you can change that to a button
  2. 将手势识别器添加到imageView中,您可以将其更改为按钮
  3. Add a button over the image view (no title or image for it)
  4. 在图像视图上添加一个按钮(没有标题或图像)

Then create an @IBAction for the button/gesture recogniser, and a delegate method that will call the main viewController where you can pass all the data you need from the cell to instantiate the second VC

然后为按钮/手势识别器创建一个@IBAction,以及一个委托方法,该方法将调用主视图控制器,在那里您可以从单元格中传递所需的所有数据,以实例化第二个VC。

Update I would advice against adding the logic of handling the tap in the cellForRow the viewController is not meant to handle and manage his child logic.

更新,我建议不要添加处理cellForRow中tap的逻辑这个视图控制器不是用来处理和管理他的子逻辑的。

#1


1  

You need to execute this code in cellForRowAt indexPath instead did select.

您需要在cellForRowAt indexPath中执行此代码,而不是选择。

As you said you want to use image id from the tag value I suggest below change in addition of adding code in cellForRowAt indexPath:

正如您说过的,您想要从标签值中使用图像id,我建议在cellForRowAt indexPath中添加代码的更改如下:

Change tapGesture code as below:

更改tapGesture code如下:

let tapGesture = UITapGestureRecognizer (target: self, action: #selector(imgTap(tapGesture:)))

And imgTap function:

和imgTap功能:

 func imgTap(tapGesture: UITapGestureRecognizer) {
        let imgView = tapGesture.view as! UIImageView
        let idToMove = imgView.tag
       //Do further execution where you need idToMove

    }

#2


2  

Yesterday itself I created sample and tried.I got the solution.But I could not post my answer immediately as I had some work.

昨天我自己制作了样品并尝试了。我得到了解决方案。但是我不能马上给出我的答案,因为我还有一些工作要做。

Now I will give you my answer.I don't expect reputation for my below answer.

现在我给你我的答案。我不指望我下面的回答有什么好名声。

When you click or tap the image first time,it navigates.

当你第一次点击或点击图像时,它会导航。

You don't need to add TapGestureRecognizer for imageView in didSelectRowAt method.You need to add TapGestureRecognizer for image View in cellForRowAt method.

在didSelectRowAt方法中,不需要为imageView添加TapGestureRecognizer。在cellForRowAt方法中,需要为图像视图添加TapGestureRecognizer。

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    let mobiles: [String] = ["iPhone", "Android"]
    let images: [String] = ["iPhone.png", "android.png"]
    @IBOutlet var tableViewImageTapping: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // number of rows in table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.mobiles.count
    }

    // create a cell for each table view row
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        var cell:UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "cell")
        if (cell == nil) {
            cell = UITableViewCell(style:UITableViewCellStyle.default, reuseIdentifier:"cell")
        }
        cell?.textLabel?.text = self.mobiles[indexPath.row]
        let strImageName = images[indexPath.row]
        cell?.imageView?.image = UIImage(named: strImageName)
        cell?.imageView?.tag = indexPath.row
        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
        tapGestureRecognizer.numberOfTapsRequired = 1
        cell?.imageView?.isUserInteractionEnabled = true
        cell?.imageView?.addGestureRecognizer(tapGestureRecognizer)
        return cell!
    }

    // method to run when table view cell is selected
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped table view cell index is \(indexPath.row).")
    }

    // method to run when imageview is tapped
    func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
    {
        let imgView = tapGestureRecognizer.view as! UIImageView
        print("your taped image view tag is : \(imgView.tag)")
        if (imgView.tag == 0) //Give your image View tag
        {
            //navigate to next view
        }
        else{

        }
    }
} 

Output Screenshot

输出屏幕截图

点击UITableView单元格内的图像

Printed results are

打印结果

When you click the first image in first click

当您单击第一个图像时,第一次单击

点击UITableView单元格内的图像

Then when you click the second image in first click

然后,当你点击第二个图像,在第一次点击

点击UITableView单元格内的图像

#3


0  

You are assigning the gesture recognizers in the "did select row at index path" method, this means that the user must select (tap) a cell for the gesture recognizers to be assigned to the images, and then the user must tap the image for those recognizers to react by calling "imgTap()", those are the two taps.

你分配的手势识别器来“选择行索引路径”方法,这意味着用户必须选择(tap)细胞的手势识别器来分配给图像,然后用户必须点击图像识别器的反应通过调用“imgTap()这是两个龙头。

What you should do instead is assign the gesture recognizers in the "cell for row at index path" method, so when you create each cell you also create the gesture recognizers, that way when the user taps an image for the first time the tap is recognized and "imgTap()" is called.

你应该做的是分配的手势识别器“细胞的行索引路径”的方法,所以当你创建每个细胞也创建手势识别器,这样当用户首次利用图像水龙头是公认的“imgTap()”。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! CustomCell

    // Configure the cell...

    let tapGesture1 = UITapGestureRecognizer (target: self, action: #selector(ItemsController.imgTap))
    cell.image1st.addGestureRecognizer(tapGesture1)
    let tapGesture2 = UITapGestureRecognizer (target: self, action: #selector(ItemsController.imgTap))
    cell.image2nd.addGestureRecognizer(tapGesture2)

    return cell
}

I also recommend changing the code a little so you can call "imgTap()" with a parameter (the id of what was tapped), instead of having 2 methods "imgTap()" and "imgTap1()".

我还建议稍微修改一下代码,以便您可以使用参数(被选中的内容的id)调用“imgTap()”,而不是使用两个方法“imgTap()”和“imgTap1()”。

#4


0  

  1. Please don't use force unwrap as! prodctCell
  2. 请不要使用强制打开包装!prodctCell
  3. Please use name swift naming conventions
  4. 请使用名称swift命名约定
  5. Don't use .tag cell is usually reused it might break in some edge cases
  6. 不要使用。标记单元格通常在某些边界情况下被重用。

Now back to your question, you already have a custom cell that holds the image. you have several possibilities

现在回到您的问题,您已经有了一个保存映像的自定义单元格。你有几个可能性

  1. Add the gesture recogniser to the imageView you can change that to a button
  2. 将手势识别器添加到imageView中,您可以将其更改为按钮
  3. Add a button over the image view (no title or image for it)
  4. 在图像视图上添加一个按钮(没有标题或图像)

Then create an @IBAction for the button/gesture recogniser, and a delegate method that will call the main viewController where you can pass all the data you need from the cell to instantiate the second VC

然后为按钮/手势识别器创建一个@IBAction,以及一个委托方法,该方法将调用主视图控制器,在那里您可以从单元格中传递所需的所有数据,以实例化第二个VC。

Update I would advice against adding the logic of handling the tap in the cellForRow the viewController is not meant to handle and manage his child logic.

更新,我建议不要添加处理cellForRow中tap的逻辑这个视图控制器不是用来处理和管理他的子逻辑的。