【问题标题】:Delegate Not Called in UICollectionReusableViewUICollectionReusableView 中未调用委托
【发布时间】:2019-11-11 09:45:56
【问题描述】:

我有一个自定义 UICollectionReusableView 作为 UICollectionView 标头。在这个视图中,我有两个按钮。我创建了一个委托方法来执行按钮操作,但是它们没有被调用。

我在UICollectionViewDataSource 中添加我的标题,如下所示;

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: Identifier.exploreCollectionReusableView, for: indexPath) as! ExploreCollectionReusableView
    return headerView
}

我设置了我的协议方法并在自定义标头中添加了一个委托变量;

protocol SelectedDidSeeAll {
    func seeAllCategories()
    func seeAllItems()
}

var delegate: SelectedDidSeeAll?

我将目标添加到按钮;

seeAllCategoriesButton.addTarget(self, action: #selector(seeAllCategories), for: .touchUpInside)
seeAllItemsButton.addTarget(self, action: #selector(seeAllItems), for: .touchUpInside)

我在 UIViewController viewDidLoad() 中将委托设置为 self

exploreCollectionReusableView.delegate = self

我实现了@objc 函数;

@objc func seeAllCategories() {
    delegate?.seeAllCategories()
}

@objc func seeAllItems() {
    delegate?.seeAllItems()
}

最后,我符合UIViewController中的委托方法;

extension ExploreViewController: SelectedDidSeeAll {

func seeAllCategories() {
    // Do Something
    print("something")
    }

func seeAllItems() {
    // Do Something
    print("something")
    }
}

委托控制台日志

打印我得到的委托时;

Optional(<bidr.ExploreViewController: 0x7fd466e5d0b0>)

所以我假设我已经完成了实现委托方法所需的一切,但是,单击按钮没有任何效果。

【问题讨论】:

    标签: ios swift uicollectionview delegates uicollectionreusableview


    【解决方案1】:

    collectionView(_: viewForSupplementaryElementOfKind: at:) 中设置delegate 而不是viewDidLoad(),即

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: Identifier.exploreCollectionReusableView, for: indexPath) as! ExploreCollectionReusableView
        headerView.delegate = self
        return headerView
    }
    

    viewDidLoad() 中,exploreCollectionReusableView 可能未设置。

    【讨论】:

    • 我的数据源是一个自定义的 UICollectionViewDataSource 类,因此不可能。
    • 然后在 dataSource 中传递 ViewController 的实例并使用它来设置委托。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 2014-03-18
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多