首页 > 解决方案 > Swift UICollectionView 没有调用方法 didSelectItemAt

问题描述

我一直在尝试创建一个自定义 collectionView,但由于func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)某种原因该方法不起作用。

我将其添加UICollectionViewDelegate到控制器中,但无法正常工作。这里有一些代码:

//
//  PacotesViagensViewController.swift
//  Alura Viagens
//
//  Created by Guilherme Golfetto on 04/01/21.
//

import UIKit

class PacotesViagensViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,UICollectionViewDelegate, UISearchBarDelegate {
            
    @IBOutlet weak var pacotesViagem: UICollectionView!
    
    @IBOutlet weak var pesquisarViagens: UISearchBar!
    
    @IBOutlet weak var labelContadorPacotes: UILabel!
    let listaComTodasViagens:Array<Viagem> = ViagemDAO().retornaTodasAsViagens();
    
    var listaViagens:Array<Viagem> = []
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        listaViagens = listaComTodasViagens;
        pacotesViagem.dataSource = self
        pacotesViagem.delegate = self;
        pesquisarViagens.delegate = self;
        self.labelContadorPacotes.text = self.atualizaContagemLabel();

    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.listaViagens.count;
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let celulaPacote = collectionView.dequeueReusableCell(withReuseIdentifier: "celulaPacote", for: indexPath) as! PacoteViagemCollectionViewCell;
        
        let viagem = listaViagens[indexPath.row];
        
        celulaPacote.labelTitulo.text = viagem.titulo;

        return celulaPacote;
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        //dividido por dois porque são duas colunas
        let larguraCelula = collectionView.bounds.width / 2;
        return CGSize(width: larguraCelula - 15, height: 160)
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("HIIII") //STILL NOT WORKING
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        listaViagens = listaComTodasViagens;
        if searchText != "" {
            // o [c] é para virar case insetivea
            //o [d] é para ignorar a acentuação
            let filtroListaViagem = NSPredicate(format: "titulo contains[c] %@", searchText);
            
            let listaFiltrada:Array<Viagem> = (listaViagens as NSArray).filtered(using: filtroListaViagem) as! Array;
            
            listaViagens = listaFiltrada;
        }
        
        self.labelContadorPacotes.text = self.atualizaContagemLabel();
        pacotesViagem.reloadData();
    }
    
    func atualizaContagemLabel() -> String {
        return listaViagens.count == 1 ? "1 pacote encontrado" : "\(listaViagens.count) pacotes encontrado";
    }

}

我是 Swift 开发的新手,我不知道我在这里缺少什么。

提前致谢

编辑1:

添加所有控制器代码

标签: iosswiftuicollectionview

解决方案


我检查了你的代码。委托模式是正确的。我认为,您必须实现数据源功能,以便集合视图可以包含一些项目。根据当前代码,集合视图中没有项目。所以 didSelectItemAt 事件现在不能发生。请参考以下代码。

extension ViewController: UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) as! MyCell
        cell.textLabel.text = String(indexPath.row + 1)
        return cell
    }
}

extension ViewController: UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print(indexPath.item + 1)
    }
}

推荐阅读