tap gesture on uiimage in collectionview - ios

In each cell of my UICollectionView, I have multiple object to interact with.
So instead of use didSelect delegate method, I really wanted to add a tap gesture on each object of the cell.
To make it simple, I removed all the other objects in the example:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! PlacesCollectionViewCell
let tap = UITapGestureRecognizer(target: self, action: "gotToSelectedPlace:")
tap.numberOfTapsRequired = 1
cell.imageView.userInteractionEnabled = true
cell.imageView.addGestureRecognizer(tap)
cell.imageView.file = places[indexPath.row].picture
cell.imageView.loadInBackground()
return cell
}
In viewDidLoad, I use a nib :
collectionView.registerNib(UINib(nibName: "PlacesCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell")
UICollectionView Settings:
Delays Content Touches: True
Cancellable Content Touches: True
With this example, I can't handle the tap gesture. Nothing happen.
Did I miss something??
Thanks

try this one
var doubletapgesture : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "processDoubleTap:")
doubletapgesture.numberOfTapsRequired = 1
collectionView.addGestureRecognizer(doubletapgesture)
now handle gesture
func processDoubleTap (sender: UITapGestureRecognizer)
{
if sender.state == UIGestureRecognizerState.Ended
{
var point:CGPoint = sender.locationInView(collectionView)
var indelPath:NSIndexPath =collectionView.indexPathForItemAtPoint(point)
if indexPath
{
println("image taped")
}
else
{
//Do Some Other Stuff Here That Isnt Related;
}
}
}

Related

How to avoid adding more than one tap gesture to any cell?

I have a weird problem. When scrolling down, cells disappear if Tap Gesture happened.
Looks like I need to stop adding Tap Gesture to cells. I've done testing of this condition in function but it didn't work.
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ToDoItemsCell
...
cell.textField.delegate = self
cell.textField.isHidden = true
cell.toDoItemLabel.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toDoItemLabelTapped))
tapGesture.numberOfTapsRequired = 1
cell.addGestureRecognizer(tapGesture)
return cell
}
And here is my function:
#objc func toDoItemLabelTapped(_ gesture: UITapGestureRecognizer) {
if gesture.state == .ended {
let location = gesture.location(in: self.tableView)
if let indexPath = tableView.indexPathForRow(at: location) {
if let cell = self.tableView.cellForRow(at: indexPath) as? ToDoItemsCell {
cell.toDoItemLabel.isHidden = true
cell.textField.isHidden = false
cell.textField.becomeFirstResponder()
cell.textField.text = cell.toDoItemLabel.text
}
}
}
}
Tapping works, but it keeps adding to other cells and makes them disappear. What can be the issue?
Gesture should be added once to each cell. In your code gesture will be added every time cellForRowAt will be called and it will be called many times especially when you scroll down to list.
Move you gesture add code to ToDoItemsCell class and than you can use delegates to inform your view controller when cell gets tapped.
protocol ToDoItemsCellDelegate {
toDoItemsCellDidTapped(_ cell: ToDoItemsCell)
}
class ToDoItemsCell : UITableViewCell {
weak var delegate: ToDoItemsCellDelegate?
var indexPath: IndexPath!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// code common to all your cells goes here
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toDoItemLabelTapped))
tapGesture.numberOfTapsRequired = 1
self.addGestureRecognizer(tapGesture)
}
#objc func toDoItemLabelTapped(_ gesture: UITapGestureRecognizer) {
delegate?.toDoItemsCellDidTapped(self)
}
}
In function cellForRowAt you can just select the delegate and set indexPath.
Note:
If you just wanted to perform action when user taps any cell you can use didSelectRowAt method of UITableViewDelegate.

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

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")
}
}
}
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?
You are adding gesture recognizer on your tableview instead of imageView as you required. Yo need to move your code from viewDidLoad to cellForRowAtIndexPath and add gesture to imageView in each cell while configuing your cell.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
var recognizer = UITapGestureRecognizer(target: self, action: #selector(tapEdit(recognizer:)))
// Add gesture recognizer to your image view
cell.yourimageview.addGestureRecognizer(recognizer)
}
Note: Do make sure to enable userinteraction of your image view
cell.yourimageview.userInteractionEnabled = YES;
For your requirement I will suggest using UILongPressGestureRecognizer as it has less chances of conflict in gesture and didselect. Yo can add UILongPressGestureRecognizer in viewDidLoad and access it as per your requirement.
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.handleLongPress(_:)))
lpgr.minimumPressDuration = 1
tableView.addGestureRecognizer(lpgr)
Define method as
func handleLongPress(_ gesture: UILongPressGestureRecognizer){
if gesture.state != .began { return }
let tapLocation = gesture.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")
}
}
You can try removing if recognizer.state == UIGestureRecognizerState.ended condition from your method.
UITapGestureRecognizer is a discrete gesture, and as such, your event handler is called only once when the gesture was recognized. You don't have to check the state at all. Certainly you won't receive a call for the state of .Began. For more info consider #Rob ans here.
Add This line in cell for row at index path
var recognizer = UITapGestureRecognizer(target: self, action: #selector(tapEdit(recognizer:)))
// Add gesture recognizer to the view
cell.yourimageviewname.addGestureRecognizer(recognizer)
cell.yourimageviewname.userInteractionEnabled = true;
For my suggestion you have to use UIButton in cell, for performance
improvements,
UIButtons
Specially designed for this and have been extensively optimized by Apple for touches.
If you want image in cell you can use UIButton with Image inside.
I have had design a solution like this. I just write a sample code below:
import UIKit
protocol CellImageTapDelegate {
func tableCell(didClickedImageOf tableCell: UITableViewCell)
}
class SampleCell : UITableViewCell {
var delegate : CellImageTapDelegate?
var tapGestureRecognizer = UITapGestureRecognizer()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
tapGestureRecognizer.addTarget(self, action: #selector(SampleCell.imageTapped(gestureRecgonizer:)))
self.addGestureRecognizer(tapGestureRecognizer)
}
func imageTapped(gestureRecgonizer: UITapGestureRecognizer) {
delegate?.tableCell(didClickedImageOf: self)
}
}
class ViewController: UITableViewController, CellImageTapDelegate {
// CellImageTapDelegate
func tableCell(didClickedImageOf tableCell: UITableViewCell) {
if let rowIndexPath = tableView.indexPath(for: tableCell) {
print("Row Selected of indexPath: \(rowIndexPath)")
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SampleCellID", for: indexPath) as! SampleCell
cell.delegate = self
return cell
}
}
remember to do following in storyboard
1. enable user interaction of imageview
2. set class of tableviewcell
3. set reuse identifier of tableviewcell
// create an instance of UITapGestureRecognizer and tell it to run
// an action we'll call "handleTap:"
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
// we use our delegate
tap.delegate = self
// allow for user interaction
cell.imageViewName.userInteractionEnabled = true
// add tap as a gestureRecognizer to tapView
cell.imageViewName.addGestureRecognizer(tap)
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

Selector to get indexPath UICollectionView Swift 3.0

I'm trying to get indexPath on the cell when it is tapped twice.
I'm passing arguments in Selector like this but it is giving error.
What is the correct format for this ?
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let subOptioncell : SubOptionsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: subOptionsCVReuseIdentifier, for: indexPath) as! SubOptionsCollectionViewCell
let imageNamed = "\(customizeOptionSelected[indexPath.row])"
subOptioncell.subOptionsImage.image = UIImage(named: imageNamed)
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped(sender: indexPath)))
tap.numberOfTapsRequired = 2
collectionView.addGestureRecognizer(tap)
return subOptioncell
}
}
func doubleTapped(sender: IndexPath) {
print("Double Tap")
}
First of all you are adding tapGesture to collectionView instead of subOptioncell.
It should be:
subOptioncell.addGestureRecognizer(tap)
Instead of:
collectionView.addGestureRecognizer(tap)
You cannot pass other instance with selector of UIGestureRecognizer, the only instance you can pass is UI(Tap)GestureRecognizer. If you want the indexPath of that cell you can try like this. First of all set your selector of TapGesture like this.
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped(sender:)))
Now method should be like:
func doubleTapped(sender: UITapGestureRecognizer) {
if let cell = sender.view as? SubOptionsCollectionViewCell, let indexPath = self.collectionView.indexPath(for: cell) {
print(indexPath)
}
}
Edit: If you want to show/hide image on cell double tap then you need to handle it using indexPath of cell, for that first declare one instance of IndexPath and use it inside cellForItemAt indexPath.
var selectedIndexPaths = IndexPath()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//Your code
//Now add below code to handle show/hide image
cell.subOptionSelected.isHidden = self.selectedIndexPaths != indexPath
return cell
}
Now on doubleTapped action of UITapGestureRecognizer set the selectedIndexPath.
func doubleTapped(sender: UITapGestureRecognizer) {
if let cell = sender.view as? SubOptionsCollectionViewCell, let indexPath = self.collectionView.indexPath(for: cell) {
if self.selectedIndexPaths == indexPath {
cell.subOptionSelected.isHidden = true
self.selectedIndexPaths = IndexPath()
}
else {
cell.subOptionSelected.isHidden = false
self.selectedIndexPaths = indexPath
}
}
}
The correct selector in your case is doubleTapped:. That is
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped:))
You can not fire arbitrary parameter when the target method is called. You can set target on subOptioncell by
let tap = UITapGestureRecognizer(target: subOptioncell, action: #selector(doubleTapped:))
And you can set whatever arbitrary object.parameter you want in subOptioncell
You need to add Selector like this way
let tap = UITapGestureRecognizer(target: self, action: #selector(YourViewControllerName.doubleTapped(_:)))
subOptioncell.addGestureRecognizer(tap)
Change your code to.
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped(_:)))
and the function to.
func doubleTapped(_ sender: AnyObject) {
print("Double Tap")
}
At your Datasource method
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let subOptioncell : SubOptionsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: subOptionsCVReuseIdentifier, for: indexPath) as! SubOptionsCollectionViewCell{
//... your code
subOptioncell.addGestureRecognizer(tap)
return subOptioncell
}
}
Then at the function cellTapped()
func cellTapped(sender: UITapGestureRecognizer){
let tapLocation = sender.location(in: yourCollectionView)
let indexPath : IndexPath = yourCollectionView.indexPathForItem(at: tapLocation)!
var currentIndex = 0
if let cell = yourCollectionView.cellForItem(at: indexPath){
currentIndex = cell.tag
}
print("Your Selected Index : \(currentIndex)")
}
Happy Coding!!!

Display button when UICollectionView Cell Tapped

I'm having an Image and when user taps twice on that image then I show a button which has a tick sign as if like user has ticked that Image. I have set the button hidden at first from Storyboard.
I'm getting cell tap using this
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.subOptionsCollectionView{
let imageNamed = "\(customizeOptionSelected[indexPath.row])"
shirtImage.image = UIImage(named: imageNamed)
let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
tap.numberOfTapsRequired = 2
collectionView.addGestureRecognizer(tap)
}
}
func doubleTapped() {
print("Double Tap")
}
But how do I display that tick/button ?
put your code in cellForRowAtIndexPath instead of didSelect and disable the userInteraction of collectionView then you can set the isHidden property of the button to true in doubleTapped, but you have to change the function like this(Swift3):
func doubleTapped(selectedIndex: IndexPath) {
print("Double Tap")
}
and change the selector like this:
UITapGestureRecognizer(target: self, action: self.doubleTapped(selectedIndex: indexPath))
There is another solution:
put your code in cellForRowAtIndexPath instead of didSelect then you can set the isHidden property of the button to true in doubleTapped, but you have to change the function like this(Swift2):
func doubleTapped(sender: AnyObject) {
let buttonPosition: CGPoint = sender.convertPoint(CGPointZero, toView: self.collectionView)
let indexPath: NSIndexPath = self.collectionView.indexPathForRowAtPoint(buttonPosition)!
//you have the selected cell index
let cell = self.collectionView.cellForItemAtIndexPath(indexPath)
//now you have the cell and have access to the button
}
and add the gesture like this:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.doubleTapped(_:)))
cell.addGestureRecognizer(tapGesture)
Swift 4 Update :
#IBAction func doubleTap(_ sender: UITapGestureRecognizer) {
let buttonPosition: CGPoint = sender.location(in: self.collectionView)
guard let indexPath = self.collectionView?.indexPathForItem(at: buttonPosition) else { return }
print ("doubleTap on cell at: ", indexPath)
let cell = self.collectionView.cellForItem(at: indexPath)
// now you have the cell and have access to the button
}

Finding the indexPath of a cell with a gesture recogniser in handler method

I have a pan gesture recogniser on a UITableViewCell which is attached to a method called didPan(sender: UIPanGestureRecognizer).
How can I use this method to determine which cell in a tableView this was activated from?
A good way to do this is to add the gesture recognizer in the UITableViewCell subclass and also have a delegate property in that class as well. So in your subclass:
protocol MyCustomCellDelegate {
func cell(cell: MyCustomCell, didPan sender: UIPanGestureRecognizer)
}
class MyCustomCell: UITableViewCell {
var delegate: MyCustomCellDelegate?
override func awakeFromNib() {
let gesture = UIPanGestureRecognizer(target: self, action: "panGestureFired:")
contentView.addGestureRecognizer(gesture)
}
func panGestureFired(sender: UIPanGestureRecognizer) {
delegate?.cell(self, didPan: sender)
}
}
Then in cellForRowAtIndexPath you just assign you view controller as the cells delegate.
You could add your pan gesture to the UITableViewCell in cellForRowAtIndexPath.
Then extract the optional UITableViewCell and look up the indexPath in the tableView.
Make sure you setup the UITableView as an IBOutlet so you can get to it in didPan:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PanCell", forIndexPath: indexPath)
let panGesture = UIPanGestureRecognizer(target: self, action: "didPan:")
cell.addGestureRecognizer(panGesture)
return cell
}
func didPan(sender: UIPanGestureRecognizer) {
// Sender will be the UITableViewCell
guard let cell = sender.view as? UITableViewCell else {
return
}
let indexPathForPan = tableView.indexPathForCell(cell)
}

Resources