我正在尝试使用 segue 从一个 VC(其中包含已实现的 Xib 文件)转到另一个 VC。
但是,我收到了一个错误
<块引用>在范围内找不到“performSegue”
这是我的xib文件的类:
class PetNameInfoCollectionViewCell: UICollectionViewCell {
@IBAction func takeAPhoto(_ sender: UIButton) {
performSegue(withIdentifier: "UIImagePickerSegue", sender: nil)
}
}
答案 0 :(得分:0)
performSegue
是 UIViewController
的方法之一,因此它不适用于 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
}
}