我有一个自定义的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>)因此,我假设我已经完成了实现委托方法所需的所有操作,但是,单击按钮没有任何效果。
发布于 2019-11-11 17:51:36
在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。
https://stackoverflow.com/questions/58798964
复制相似问题