gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:27:09 24 4
gpt4 key购买 nike

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

类型的类中向该按钮添加一个 Action

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

@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 属性。

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

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

然后在header中添加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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com