【问题标题】:Button in header use to push new view controller标题中的按钮用于推送新的视图控制器
【发布时间】:2016-12-05 20:09:58
【问题描述】:

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

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

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

    }

错误信息:value of type 'className' has no member 'storyboard'

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

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

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

    您需要在包含它的 viewController 中而不是在可重用视图中执行该转换。为了做到这一点,你需要一个自定义委托或一个回调块来告诉视图控制器标题被点击并触发推送。

    使用块/闭包/回调:

    在可重用视图中添加你的完成闭包:

    var completion: (() -> Void)?

    接下来,在您的 goToMovie func 中删除这两行并添加,然后像这样调用闭包:

    completion?()

    然后在您声明标题的视图控制器中触发转换,如下所示:

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

    使用自定义委托

    创建协议:

    protocol HeaderDelegate {
        func headerTapped(sender: UICollectionReusableView)
    }
    

    然后在头部添加委托属性

    var delegate: HeaderDelegate?
    

    那么当你声明头部时:

     . . .
    header.delegate = self
     . . .
    

    然后让视图控制器符合委托:

    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)
    
        }
    }
    

    如果视图控制器不需要知道哪个标头被点击,您可以从委托函数中删除 sender: UITableViewCell 参数。

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

    【讨论】:

    • 在课堂上我应该在哪里写var completion: (() -> Void)?
    • 这些行headerView.completion = { let storyboard . . . etc我把它放在哪里?
    • var completion: (() -> Void)? 应该放在头文件中的任何位置。当您在 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView 中声明标题时,第二个进入视图控制器
    • 对不起,当我说头文件时,我意识到这可能会造成混淆。你是对的,它只需要在课堂内的任何地方找到UICollectionReusableView
    • 如果此答案帮助您解决了问题,请标记为正确。如果没有,我很乐意帮助您实施。
    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多