如何使用 segue 从 Xib 文件加载 viewController?斯威夫特 5

Posted

技术标签:

【中文标题】如何使用 segue 从 Xib 文件加载 viewController?斯威夫特 5【英文标题】:How to Load a viewController from a Xib file using segue? Swift 5 【发布时间】:2021-08-13 13:38:11 【问题描述】:

我正在尝试使用 segue 从一个 VC(其中包含已实现的 Xib 文件)转到另一个 VC。

但是,我收到了一个错误

在范围内找不到“performSegue”

这是我的 xib 文件的类:

class PetNameInfoCollectionViewCell: UICollectionViewCell 
    @IBAction func takeAPhoto(_ sender: UIButton) 
        performSegue(withIdentifier: "UIImagePickerSegue", sender: nil)
    

【问题讨论】:

【参考方案1】:

performSegueUIViewController 的方法之一,因此它不适用于UICollectionViewCell。相反,您需要从包含集合视图的父视图控制器调用 performSegue

您可以为此使用委托或闭包,但我更喜欢闭包。首先在PetNameInfoCollectionViewCell里面加一个:

class PetNameInfoCollectionViewCell: UICollectionViewCell 
    var photoTapped: (() -> Void)? /// here!

    @IBAction func takeAPhoto(_ sender: UIButton) 
        photoTapped?() /// call it
    

然后,在父视图控制器的cellForItemAt 中分配闭包。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
    if indexPath.item == 0 
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: userNameInfoCollectionViewCellId, for: indexPath) as! userNameInfoCollectionViewCell /// replace with the cell class
        cell.photoTapped =  [weak self] in
            self?.performSegue(withIdentifier: "UIImagePickerSegue", sender: nil)
        
        return cell
        
     else 
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PetNameInfoCollectionViewCell, for: indexPath) as! PetNameInfoCollectionViewCell /// replace with the cell class
        cell.photoTapped =  [weak self] in
            self?.performSegue(withIdentifier: "UIImagePickerSegue", sender: nil)
        
        return cell
    

【讨论】:

您好,谢谢您的回答!我正在使用 cellForItemAt 方法更改我的 collectionView 中的单元格,如下所示: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell if indexPath.item == 0 return collectionView.dequeueReusableCell(withReuseIdentifier: userNameInfoCollectionViewCellId , for: indexPath) else return collectionView.dequeueReusableCell(withReuseIdentifier: PetNameInfoCollectionViewCell, for: indexPath) 如何在里面添加闭包? @Swifty_Man 编辑了我的答案。您需要执行let cell = collectionView.dequeueReusableCell 才能获得对单元格的引用。然后,配置好photoTapped之后,就可以return了。 耶!它奏效了,我花了很多时间用委托模式来做这件事,但由于不明显的原因,它对我不起作用。非常感谢! 好的,我现在学会了如何同时使用闭包和委托!

以上是关于如何使用 segue 从 Xib 文件加载 viewController?斯威夫特 5的主要内容,如果未能解决你的问题,请参考以下文章

如何从自定义集合视图单元(使用 xib 创建的单元)到 tabBar 控制器创建自定义 segue

将数据从 TableViewController 传递到 XIB 文件而不使用 Segues-Swift 3

如何使用委托Objective c从UITableViewCell.xib创建到ViewController的segue?

使用xib ios7从presentviewcontroller准备推送segue

如何执行从自定义 UITableViewCell(xib) 到另一个 ViewController 的 segue 视图

以编程方式从 Xib 执行 Segue