Adding a gesture recognizer to an image view in a table cell

Viewed 8552

How can I add a Gesture Recognizer to a UIImageView in a table cell? I want it so that if a user taps an image in the cell, the image will change and the data model will update.

I know this needs to be set up in the UITableViewController. My code currently can execute a command if anywhere in the cell is tapped, but I would like it to execute only if the image is tapped, not anywhere in the cell.

I setup up the gesture recognizer in viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()

    // Load sample data
    loadSampleHabits()

    // Initialize tap gesture recognizer
    var recognizer = UITapGestureRecognizer(target: self, action: #selector(tapEdit(recognizer:)))
    // Add gesture recognizer to the view
    self.tableView.addGestureRecognizer(recognizer)

And this is the function

//action method for gesture recognizer
func tapEdit(recognizer: UITapGestureRecognizer) {
    if recognizer.state == UIGestureRecognizerState.ended {
        let tapLocation = recognizer.location(in: self.tableView)
        if let tapIndexPath = self.tableView.indexPathForRow(at: tapLocation) {
            if let tappedCell = self.tableView.cellForRow(at: tapIndexPath) as? HabitTableViewCell {
                print("Row Selected")

            }
        }
    }

What the cell looks like

As a secondary question, are there any conflicts if I want to add a gesture recognizer to the cell and the image view within the cell?

6 Answers
import UIKit

class UserInfoCell: UITableViewCell{

    @IBOutlet weak var imagePlaceholder: UIImageView!
}

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    @IBOutlet weak var tableView: UITableView!


    let imagePicker = UIImagePickerController()
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 1


    }

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

            let cell = tableView.dequeueReusableCell(withIdentifier: "UserInfoCell" ,for: indexPath ) as! UserInfoCell
            let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.openGallery))

            cell.imagePlaceholder.addGestureRecognizer(recognizer)
            recognizer.numberOfTapsRequired = 1
            cell.imagePlaceholder.isUserInteractionEnabled = true
            cell.name.text = "Akshay"

            if let data = UserDefaults.standard.data(forKey: "savedImage") {
                cell.imagePlaceholder.image = UIImage(data: data as Data)
            }

            return cell




    }
    @objc func openGallery(){
        imagePicker.sourceType = .photoLibrary
        present(imagePicker,animated:  true, completion: nil)
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        let userimage = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        let imageData = userimage.jpegData(compressionQuality: 1)!
        UserDefaults.standard.setValue(imageData, forKey: "savedImage")
        print("image found")
        self.imagePicker.dismiss(animated: true, completion: nil)

        self.tableView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        imagePicker.delegate = self
tableView.tableFooterView = UIView()

    }
}

This code select image from gallery using Tapgesture of ImageView inside a TableViewCell

Related