我创建了一个自定义类,它是的子类UICollectionReusableView
。它本质上是一个Collection View的section标头,我在上面添加了一些按钮。当按下按钮时,我希望视图控制器过滤结果(取决于按下哪个按钮)。
我需要我的视图控制器为该自定义类提供一个出口,但是那没有用,因为Xcode抱怨具有类的重复内容(即使我只打算使用一个collectionView节头)。因此,我的下一个选择是委派。
我的问题有两个:
如何将自定义类的委托设置为视图控制器?通常情况下,我将委托设置在其中,prepareForSegue
但是由于没有代理,我不确定该怎么做。我的视图控制器是在情节提要中创建的,而我的自定义类没有对其的引用。即使在我的View Controller中,我也无法访问集合视图的节标题以将其委托设置为self(我检查了Apple的文档,没有任何属性可以访问节标题)。
在将IBAction
s设置为自定义类时,如何确保被点击的按钮也作为发送者传递进来?我已经将按钮之一连接到一个动作上并编写了代码,func someAction (sender: AnyObject) {}
但是程序如何知道按钮本身应该作为发送者传递呢?
这是我的代码:
// Custom Class
class CollectionHeaderView: UICollectionReusableView {
@IBAction func buttonPressed (sender: AnyObject) {
**delegate?.didTapButton(self)**
}
var delegate: UICollectionViewDelegate?
}
// Protocol
protocol CollectionHeaderViewDelegate {
func didTapButton(sender: CollectionHeaderView)
}
// View Controller (the delegate)
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "CollectionHeaderView", forIndexPath: indexPath) as! CollectionHeaderView
headerView.delegate = self
return headerView
}
extension BrowseViewController: CollectionHeaderViewDelegate {
func didTapButton(sender: CollectionHeaderView) {
print("Delegate's Button Tapped")
}
}
粗体部分是Xcode给我的错误提示,“类型为UICollectionViewDelegate的值没有成员'Did Tap Button'”-不知道为什么要引用UICollectionViewDelegate。 headerViewDelegate的委托,但仍然给出错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句