Display button when UICollectionView Cell Tapped - ios

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
}

Related

Swipe gesture in tableview

I want to add Swipe gesture on my cell. It work fine.but the Problem is when i swipe on first cell but my fifth cell also swipe. I know this indexpath problem. Please help.But i am stuck from few hour.
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.handleLeftSwipe))
swipeLeft.direction = UISwipeGestureRecognizerDirection.left
table.addGestureRecognizer(swipeLeft)
let swipeLeftd = UISwipeGestureRecognizer(target: self, action: #selector(self.handleLeftSwipes))
swipeLeftd.direction = UISwipeGestureRecognizerDirection.right
table.addGestureRecognizer(swipeLeftd)
#objc func handleLeftSwipe(sender: UITapGestureRecognizer) {
print("rigt called")
let location = sender.location(in: self.table)
let indexPath = self.table.indexPathForRow(at: location)
let cell = self.table.cellForRow(at: indexPath!) as! TableViewCell
print("swipe")
cell.myView.frame.origin.x = -94
}
#objc func handleLeftSwipes(sender: UITapGestureRecognizer) {
print("labelSwipedLeft called")
let location = sender.location(in: self.table)
let indexPath = self.table.indexPathForRow(at: location)
let cell = self.table.cellForRow(at: indexPath!) as! TableViewCell
print("swipe")
cell.myView.frame.origin.x = 80
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "TableViewCell"
var cell: TableViewCell! = tableView.dequeueReusableCell(withIdentifier: identifier) as? TableViewCell
if cell == nil {
var nib : Array = Bundle.main.loadNibNamed("TableViewCell",owner: self,options: nil)!
cell = nib[2] as? TableViewCell
}
return cell!
}
The reason for that is reusing your cells. I assume you do not set anything in your prepareForReuse(). So, your problem is in line cell.myView.frame.origin.x = 80, right? Just set it to default in prepareForReuse or in cellForRowAt indexPath.

How to get the get a index.row and index section from a UITableViewCell with an UIStepper programmatically using Swift 4 [duplicate]

I have table view cells like quiz. And in each cell I have a buttons And how can I identify in which cell button was pressed. Maybe by IndexPath???
This is how I connected button to
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionCell")!
variant1 = cell.contentView.viewWithTag(1) as! UIButton
variant2 = cell.contentView.viewWithTag(2) as! UIButton
variant3 = cell.contentView.viewWithTag(3) as! UIButton
variant4 = cell.contentView.viewWithTag(4) as! UIButton
variant1.addTarget(self, action: #selector(self.variant1ButtonPressed), for: .touchUpInside)
variant2.addTarget(self, action: #selector(self.variant2ButtonPressed), for: .touchUpInside)
variant3.addTarget(self, action: #selector(self.variant3ButtonPressed), for: .touchUpInside)
variant4.addTarget(self, action: #selector(self.variant4ButtonPressed), for: .touchUpInside)
return cell
}
func variant1ButtonPressed() {
print("Variant1")
variant1.backgroundColor = UIColor.green
}
func variant2ButtonPressed() {
print("Variant2")
variant2.backgroundColor = UIColor.green
}
func variant3ButtonPressed() {
print("Variant3")
variant3.backgroundColor = UIColor.green
}
func variant4ButtonPressed() {
print("Variant4")
variant4.backgroundColor = UIColor.green
}
This is how it looks like in Storyboard:
You should use delegate pattern, basic example:
protocol MyCellDelegate {
func didTapButtonInside(cell: MyCell)
}
class MyCell: UITableViewCell {
weak var delegate: MyCellDelegate?
func buttonTapAction() {
delegate?.didTapButtonInside(cell: self)
}
}
class ViewController: MyCellDelegate {
let tableView: UITableView
func didTapButtonInside(cell: MyCell) {
if let indexPath = tableView.indexPath(for: cell) {
print("User did tap cell with index: \(indexPath.row)")
}
}
}
Use this line to get indexPath, Where you have to pass UIButton on target selector
func buttonTapped(_ sender:AnyObject) {
let buttonPosition:CGPoint = sender.convert(CGPointZero, to:self.tableView)
let indexPath = self.tableView.indexPathForRow(at: buttonPosition)
}
Since actions need to be inside the view controller, ctrl + drag from your button to the view controller - this will use the responder chain.
Basically you need to convert the view (button) to the coordinate system of the table view in order to tell what is the IndexPath and if you have the IndexPath you have the object that corresponds to the button inside the cell that was tapped:
#IBAction func buttonTapped(_ sender: Any) {
if let indexPath = indexPath(of: sender) {
// Your implementation...
}
}
private func indexPath(of element:Any) -> IndexPath? {
if let view = element as? UIView {
// Converting to table view coordinate system
let pos = view.convert(CGPoint.zero, to: self.tableView)
// Getting the index path according to the converted position
return tableView.indexPathForRow(at: pos) as? IndexPath
}
return nil
}
It is important to mention that there many solutions for your question. But you should know that in Apple's sample projects they also use this technic.
This is how you add tag to a UIButton inside UITableView, add below lines of code in
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
cell.yourButton.tag = indexPath.row
cell.yourButton.addTarget(self, action:#selector(btnPressed(sender:)), for: .touchUpInside)
Add this function in your ViewController
func btnPressed(sender: UIButton)
{
print("Button tag \(sender.tag)")
}
Hope this helps...
Simple Subclass button just like JSIndexButton
class JSIndexButton : UIButton {
var indexPath : IndexPath!
}
Now at cellForRowAt
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ItemCell
let itemCategory = dataList[button.indexPath.section];
let item = itemCategory.items[button.indexPath.row];
cell.imgView.setImageWithURL(item.photoUrl);
cell.btnBuy.indexPath = indexPath;
cell.btnBuy.addTarget(self, action: #selector(JSCollapsableTableView.btnBuyPressed(_:)), for: UIControlEvents.touchUpInside)
return cell;
}
Check Button Action
#IBAction func btnBuyPressed(_ button: JSIndexButton) {
let itemCategory = dataList[button.indexPath.section];
let item = itemCategory.items[button.indexPath.row];
}
#objc func ItemsDescription(_ sender: UIButton?,event: AnyObject?) {
let touches: Set<UITouch>
touches = (event?.allTouches!)!
let touch:UITouch = (touches.first)!
let touchPosition:CGPoint = touch.location(in: self.tableView)
let indexPath:NSIndexPath = self.tableView.indexPathForRow(at: touchPosition)! as NSIndexPath
}
adding target
cell.ItemsDescription.addTarget(self, action: #selector(ItemsDescription(_:event:)), for: UIControlEvents.touchUpInside)

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!!!

tap gesture on uiimage in collectionview

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;
}
}
}

Resources