如何使用 segue 从 Xib 文件加载 viewController? Swift 5

How to Load a viewController from a Xib file using segue? Swift 5

我正在尝试使用 segue 从一个 VC(内部已实现 Xib 文件)转到另一个 VC。

但是,我得到了

的错误

Cannot find 'performSegue' in scope

这是我的 xib 文件的class:

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

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