Открытие другого экрана, нажав на UICollectionViewCell - PullRequest
0 голосов
/ 24 мая 2018

У меня есть экран, который содержит UITableView и внутри некоторые UICollectionViews.enter image description here

Мне нужно нажать на UICollectionViewCell, открыть следующий экран и отправить некоторую информацию на этот новый экран.Но я не могу.

По моей структуре «следует» не работает.Мне нужна помощь, чтобы найти другой способ сделать это.

Код: - TableViewCell

class CategoriasTableViewCell: UITableViewCell {

    var db: Firestore!

    var categoriasArray = [Categorias]()

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var labelTitleCategorias: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()

        collectionView.dataSource = self
        collectionView.delegate = self

        /*Firebase*/
        let autenticacao = Auth.auth()

        autenticacao.addStateDidChangeListener { (autenticacao, usuario) in

            if let usuarioLogado = usuario {

            } else {

                //self.performSegue(withIdentifier: "checkEntrarSegue", sender: nil)

            }


        }

        db = Firestore.firestore()
        loadData()

    }

    func loadData() {
        db.collection("Categories")
            .addSnapshotListener { querySnapshot, error in
                guard let documents = querySnapshot?.documents else {
                    print("Error fetching documents: \(error!)")
                    return
                }

                self.categoriasArray = querySnapshot!.documents.flatMap({Categorias(dictionary: $0.data())})
                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                }
        }


    }

}

Код - TableView

class TabHomeViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self


        let autenticacao = Auth.auth()
        autenticacao.addStateDidChangeListener { (autenticacao, usuario) in

            if usuario == nil {

                self.performSegue(withIdentifier: "logoutAutomatico", sender: nil)

                //....


            }

        }


    }


}


extension TabHomeViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CellSlide", for: indexPath) as! SlideTableViewCell
            return cell

        } else if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CellCategorias", for: indexPath) as! CategoriasTableViewCell
            //cell.collectionView.reloadData()
            return cell

        } else if indexPath.row == 2{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellRecomendacoes", for: indexPath) as! RecomendacoesTableViewCell
            return cell

        } else if indexPath.row == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellPromocoes", for: indexPath) as! PromocoesTableViewCell
            return cell

        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellFamosos", for: indexPath) as! FamososTableViewCell
            return cell
        }

    }

    /*func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

        if indexPath.row == 1 {
            if let cell = cell as? CategoriasTableViewCell {

                cell.collectionView.reloadData()
                print("Atualizando Collection1")

            }
        }

    }*/


}

extension TabHomeViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return 215

        case 1:


            return 200

        case 2:


            return 300

        case 3:
            return 400

        case 4:
            return 500

        default:
            return UITableViewAutomaticDimension
        }
    }

}



//COLLECTION CATEGORIAS
extension CategoriasTableViewCell: UICollectionViewDataSource {

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

        return categoriasArray.count  //Int(Constant.totalItem)
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        //set the image URL
        let urlBase = categoriasArray[indexPath.row].foto_horizontal
        let imageUrl = URL(string: urlBase)!

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "BoxCollectionCategorias", for: indexPath) as! CellCategoriasCollectionViewCell
        cell.labelNameCategoria.text = categoriasArray[indexPath.row].nome
        cell.imageView.sd_setImage(with: imageUrl) { (image, erro, cache, url) in
            // Here my code ...
        }
        return (cell)
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        print("Click... \(categoriasArray[indexPath.row].uid)")
        // Here I detect the click on the UICollectionViewCell
    }

}

extension CategoriasTableViewCell: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 130)
    }   
}

Яиспользуя расширение Category_TableViewCell: UICollectionViewDataSource {} , для редактирования UICollectionView данных

Ответы [ 2 ]

0 голосов
/ 24 мая 2018

Вам нужно вызвать переход, чтобы перейти к другому представлению, или представить свой новый вид поверх текущего представления (что я не рекомендую, если вы не знаете, что делаете).

Чтобы передать вашу информацию из одного представления в другое, у вас есть несколько вариантов:

  • передать ее через сеанс (один к одному)
  • использовать протоколы и делегаты (один к одному)
  • использовать события и наблюдателей (один ко многим)
  • использовать третий класс, ответственный за хранение текущих данных (один ко многим)
0 голосов
/ 24 мая 2018

Вы можете просто создать делегата для вашего TableViewCell

protocol CategoriasTableViewCellDelegate : class {
    func categoryTapped(_ cell: CategoriasTableViewCell, categoriasID:Int)
}

class CategoriasTableViewCell: UITableViewCell {
    weak var delegate : CategoriasTableViewCellDelegate?
}

И в категории ExtensionsTableViewCell

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

       if delegate != nil {
            delegate?.categoryTapped(self, categoriasID: categoriasArray[indexPath.row].uid)
        }
        print("Click... \(categoriasArray[indexPath.row].uid)")
        // Here I detect the click on the UICollectionViewCell
    }

При вашем TabHomeViewController наборе cell.delegate = self

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CellSlide", for: indexPath) as! SlideTableViewCell
            return cell

        } else if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "CellCategorias", for: indexPath) as! CategoriasTableViewCell
            //cell.collectionView.reloadData()
           cell.delegate = self
            return cell

        } else if indexPath.row == 2{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellRecomendacoes", for: indexPath) as! RecomendacoesTableViewCell
            return cell

        } else if indexPath.row == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellPromocoes", for: indexPath) as! PromocoesTableViewCell
            return cell

        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cellFamosos", for: indexPath) as! FamososTableViewCell
            return cell
        }

    }

// теперь вы можете получить данные в TabHomeViewController

extension TabHomeViewController:CategoriasTableViewCellDelegate {

        func categoryTapped(_ cell: CategoriasTableViewCell, categoriasID:Int){

    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...