【问题标题】:Setting my Custom Class' Delegate to my View Controller将我的自定义类的委托设置为我的视图控制器
【发布时间】:2016-08-12 13:48:18
【问题描述】:

我创建了一个自定义类,它是UICollectionReusableView 的子类。它本质上是一个集合视图的部分标题,我在上面添加了一些按钮。当按下按钮时,我希望视图控制器过滤结果(取决于按下哪个按钮)。

我需要我的视图控制器为这个自定义类提供一个出口,但这不起作用,因为 Xcode 抱怨重复的内容具有类(即使我只打算使用一个 collectionView 部分标题)。所以我的下一个选择是委托。

我的问题有两个:

  1. 如何将自定义类的委托设置为视图控制器?通常我将代理设置为prepareForSegue,但由于我没有,我不知道该怎么做。我的视图控制器是在情节提要中创建的,我的自定义类没有引用它。即使在我的视图控制器中,我也无法访问集合视图的部分标题以将其委托设置为 self(我检查了 Apple 的文档,并且没有访问部分标题的属性)。

  2. 当我为我的自定义类设置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


    【解决方案1】:

    如果此 UICollectionReusableView 是集合视图的部分标题,您可以在代码中创建它。您需要实现collectionView:viewForSupplementaryElementOfKind:atIndexPath:。此时,您(视图控制器)正在创建节标题,并且可以按照您喜欢的任何方式对其进行配置。

    或者,如果这个 UICollectionReusableView 是由情节提要中的流布局创建的,则将按钮放入情节提要中,然后像往常一样连接它们的动作。

    但是程序如何知道按钮本身应该作为发送者传入

    当点击按钮并触发其控制事件动作时,按钮本身总是作为参数提供。这就是控件的一部分。

    【讨论】:

    • 谢谢!这为我释放了巨大的潜力!哈哈。
    猜你喜欢
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多