ios - 标题中的按钮用于推送新的 View Controller

标签 ios swift uicollectionview

我有一个带标题的 UICollectionView。我在这个标题按钮中添加了, 然后我为这个 UICollectionReusableView 类型的 header 创建了一个类。然后我尝试在 UICollectionReusableView 类型的类中向该按钮添加一个操作

但是,当我写这行时,我遇到了错误

@IBAction func goToMovie(_ sender: AnyObject) {
        let st = self.storyboard?.instantiateViewController(withIdentifier: "aaa") as! aaa
        self.navigationController?.pushViewController(st, animated: true)

    }

错误消息:类型“className”的值没有成员“storyboard”

如何通过此按钮转到其他 View ?

最佳答案

您收到的错误是因为 UICollectionReusableView 没有 storyboard 属性。它也没有 navigationController 属性。

您需要不在可重用 View 中执行该转换,而是从包含它的 viewController 中执行该转换。为此,您需要自定义委托(delegate)或回调 block ,以便告诉 View Controller 标题已被点击并触发推送。

使用 block /闭包/回调:

在可重用 View 中添加完成闭包:

var 补全:(() -> Void)?

接下来,在您的 goToMovie 函数中删除这两行并添加然后调用闭包,如下所示:

完成?()

然后在声明标题的 View Controller 中触发转换,如下所示:

 . . .
headerView.completion = {
    let storyboard = UIStoryboard(name: "WhateverYourSBNameIs",  bundle: nil)
    let aaaVC = storyboard.instantiateViewController(withIdentifier: "WhateverYourIdentifierIs") as! AAAViewController
    self.navigationController?.pushViewController(st, animated: true)
}

使用自定义委托(delegate)

创建协议(protocol):

protocol HeaderDelegate {
    func headerTapped(sender: UICollectionReusableView)
}

然后在标题中添加委托(delegate)属性

var delegate: HeaderDelegate?

然后当你声明标题时:

 . . .
header.delegate = self
 . . .

然后使 View Controller 符合委托(delegate):

extension ViewController: HeaderDelegate {

    func headerTapped(sender: UITableViewCell) {
        let storyboard = UIStoryboard(name: "WhateverYourSBNameIs",  bundle: nil)
        let aaaVC = storyboard.instantiateViewController(withIdentifier: "WhateverYourIdentifierIs") as! AAAViewController
        self.navigationController?.pushViewController(st, animated: true)

    }
}

如果 View Controller 不需要知道哪个 header 被点击,您可以从委托(delegate)函数中删除 sender: UITableViewCell 参数。

希望这有帮助。我个人会使用 FWIW 闭包。

关于ios - 标题中的按钮用于推送新的 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40982477/

相关文章:

ios - 如何在 Objective c 中使用 SAP WSDL 服务?

ios - uiwebview 换行长字

ios - 如何正确连接到 Google Cast 设备并使用自定义接收器转换 url?

ios - CollectionView 底部的阴影

ios - UICollectionView reloadData 不工作

ios - OpenGL 在 iOS 12 中被弃用,如何在 iOS 12+ 设备上安全地继续使用 openGL?

ios - NSLocale 大部分是空的 - 属性在哪里?

ios - UICollectionView 更新单个单元格

iOS以编程方式添加约束导致错误

ios - 如何在 iOS 中从一个页面传递模型类数据?