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) }@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.
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... } }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
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 = trueAgregue este código a la celda de vista de colección.