【发布时间】:2016-08-12 13:48:18
【问题描述】:
我创建了一个自定义类,它是UICollectionReusableView 的子类。它本质上是一个集合视图的部分标题,我在上面添加了一些按钮。当按下按钮时,我希望视图控制器过滤结果(取决于按下哪个按钮)。
我需要我的视图控制器为这个自定义类提供一个出口,但这不起作用,因为 Xcode 抱怨重复的内容具有类(即使我只打算使用一个 collectionView 部分标题)。所以我的下一个选择是委托。
我的问题有两个:
如何将自定义类的委托设置为视图控制器?通常我将代理设置为
prepareForSegue,但由于我没有,我不知道该怎么做。我的视图控制器是在情节提要中创建的,我的自定义类没有引用它。即使在我的视图控制器中,我也无法访问集合视图的部分标题以将其委托设置为 self(我检查了 Apple 的文档,并且没有访问部分标题的属性)。当我为我的自定义类设置
IBActions 时,如何确保被点击的按钮也作为发送者传入?我已将其中一个按钮连接到一个操作并写了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,但它仍然给出了错误。
【问题讨论】:
标签: ios swift delegates protocols