【问题标题】:How to Load a viewController from a Xib file using segue? Swift 5如何使用 segue 从 Xib 文件加载 viewController?斯威夫特 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)
    }
}

【问题讨论】:

    标签: storyboard segue uicollectionviewcell xib swift5


    【解决方案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了。
    • 耶!它奏效了,我花了很多时间用委托模式来做这件事,但由于不明显的原因,它对我不起作用。非常感谢!
    • 好的,我现在学会了如何同时使用闭包和委托!
    猜你喜欢
    • 1970-01-01
    • 2017-07-22
    • 2017-03-24
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    相关资源
    最近更新 更多