Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

618
Views
¿Cómo agregar un gesto para una vista dentro de una celda de vista de colección?

Estoy agregando una vista que tiene un conjunto de images(socialView) dentro de una celda de vista de colección (que también tiene otras vistas) en la que se debe realizar un clic común. Este clic no debe ser el mismo que el clic en la celda de vista de colección.

Estoy pensando en agregar UITapGestureRecognizer para socialView cada vez en el método de delegado de CollectionView cellForItemAt . Pero quiero saber si es el camino correcto? Además, quiero obtener indexPath/position en el que se ha llamado a socialView .

 let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.socialViewTapped)) func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "bidderAuctionCell", for: indexPath) as! BidderAuctionViewCell cell.socialView.addGestureRecognizer(tapGestureRecognizer) } @objc func socialViewTapped() { // Which item cell's socialview is clicked }

ACTUALIZAR

Lo hice según las sugerencias a continuación, pero no puedo obtener dónde debo agregar UITapGestureRecognizer en la celda personalizada. La siguiente es la celda personalizada que he creado.

 class CustomViewCell: UICollectionViewCell { var index : IndexPath! var socialViewDelegate : SocialViewDelegate! @IBOutlet weak var socialView: UIView! override init(frame: CGRect) { super.init(frame:frame) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.viewTapped)) socialView.addGestureRecognizer(tapGestureRecognizer) } required init?(coder aDecoder: NSCoder) { super.init(coder:aDecoder) } @objc func viewTapped(){ socialViewDelegate.socialViewTapped(at: index) } }

No se llama a la función init. También traté de poner el inicio requerido, pero allí la vista social no está inicializada. Así que chocando

RESPUESTA FINAL

 class CustomViewCell: UICollectionViewCell { var index : IndexPath! var socialViewDelegate : SocialViewDelegate! @IBOutlet weak var socialView: UIView! override func awakeFromNib() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap)) socialView.isUserInteractionEnabled = true socialView.addGestureRecognizer(tapGesture) } @objc func handleTap(){ socialViewDelegate.socialViewTapped(at: index) } } protocol SocialViewDelegate { func socialViewTapped(at index: IndexPath) }
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

@Anurag puede resolver este problema utilizando cualquiera de los siguientes conceptos Delegación, Cierres, Notificaciones. Le sugiero que siga el patrón de delegación que iOS sigue ampliamente en sus componentes como UITableView, UICollectionView, etc.

  • Antes de implementar el patrón de delegación, agregue un reconocedor de gestos de toque a la vista.
  • En CollectionViewCell declare un método de protocolo para delegar su toque/acción
  • Confirme la implementación del delegado en su controlador de vista.
  • Implemente su método delegado en su controlador de vista.

Ejemplo de codificación:

1. Su CollectionViewCell debería verse así :

 import UIKit Protocol ViewTappedDelegate: class { func viewTapped(_ photo : String) { } } class YourCell: UICollectionViewCell, UIGestureRecognizerDelegate { @IBOutlet weak var containerView: UIView! weak var delegate : ViewTappedDelegate? override func awakeFromNib() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:))) tapGesture.delegate = self containerView.isUserInteractionEnabled = true containerView.addGestureRecognizer(tapGesture) } @objc func handleTap(recognizer:UITapGestureRecognizer) { //Call Delegate method from here... } }

2. En ViewController

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellIdentifier", for: indexPath) as! YourCell cell.delegate = self return cell } // MARK: Delegate extension YourViewController : ViewTappedDelegate { func viewTapped(_ photo : String) { // Handle delegation here... } }
over 4 years ago · Santiago Trujillo Report

0

Espero que esto funcione si aún no ha encontrado una forma de usar un protocolo como este, en su celda personalizada como esta

 import UIKit protocol CustomDelegate { func showData(indexPath: IndexPath?) } class CustomCell: UICollectionViewCell { // properties var delegate: CustomDelegate? var selectedAtIndex: IndexPath? // outlets override func awakeFromNib() { super.awakeFromNib() myView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dothis))) } @objc func dothis(){ delegate?.showData(indexPath: selectedAtIndex) } @IBOutlet weak var myView: UIView! }

escribe tu controlador de vista así

 class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CustomDelegate{ func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CustomCell cell.delegate = self cell.selectedAtIndex = indexPath return cell } func showData(indexPath: IndexPath?) { if let ip = indexPath{ print("\(ip) is the index path for tapped view") } } }

dime si esto ayuda

over 4 years ago · Santiago Trujillo Report

0

Para agregar un gesto de toque, agregue el siguiente código en la celda de su vista de colección.

 let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.socialViewTapped)) socialView?.addGestureRecognizer(tapGestureRecognizer) socialView?.isUserInteractionEnabled = true

Agregue este código a la celda de vista de colección.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!