首页 > 解决方案 > 通过 CollectionViewCell 进行 Swift 委托

问题描述

我有 big UICollectionViewCells,里面有另一个(small)UICollectionViewController,所以它基本上是有多个单元格的单元格。

问题是,我如何通知/更新我的主UICollectionViewController(有大单元格)我的小单元发生了变化UICollectionViewControllers

基本上,我cellForItemAt在 big中配置单元格UICollectionViewController,它的单元格有一个属性,didSet我在那里配置 smallUICollectionViewController

所以基本上,这是 Trello 风格的应用程序。这是我的 ListsViewController (有列表)

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ListCollectionViewCell.reuseId, for: indexPath) as! ListCollectionViewCell
        let list = lists[indexPath.row]
        cell.listName.text = "     \(list.name)"
        cell.listId = list.id
        cell.delegate = self
        cell.cards = cards[list.id]
        cell.cardsController.collectionView.reloadData()
        return cell
    }

在我的里面ListCollectionViewCell

lazy var cardsController = CardsCollectionViewController(collectionViewLayout: UICollectionViewFlowLayout())
var delegate: CardsCollectionViewControllerDelegate?
var cards: [String]? = [] {
        didSet {
            addSubview(cardsController.view)
            // constraints here
            cardsController.cards = cards ?? []
            cardsController.listId = listId
            cardsController.delegate = delegate
        }
    }

然后,在 CardsCollectionViewController 中,我有一个方法 didSelectItemAt,其中最后一张卡片就像一个按钮"Add new Card"

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


            let alert = UIAlertController(title: "Add card", message: "", preferredStyle: .alert)

            alert.addTextField()

            alert.addAction(UIAlertAction(title: "Back", style: .cancel, handler: { [] (_) in
                self.dismiss(animated: true, completion: nil)
            }))

            alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { [weak alert] (_) in
                let textField = alert?.textFields![0]
                let cardName = textField?.text

                NetworkManager.shared.createCardWith(name: cardName ?? "", onList: self.listId, completion: {
                    self.delegate?.didAddCard()
                })

            }))
        }

    }


protocol CardsCollectionViewControllerDelegate {
    func didAddCard()
}


    extension ListsViewController: CardsCollectionViewControllerDelegate {
        func didAddCard() {
            self.getDataFromTrello()
        }
    }

所有 API 网络的东西都可以正常工作,并且可以将卡片添加到 trello 本身,现在最后一部分是:当我在警报上单击“确定”时,我需要调用getDataFromTrello()方法,它是ListsViewController(first) 的方法,但我不是真的很确定我该怎么做。

标签: iosswiftuicollectionviewcell

解决方案


推荐阅读