【问题标题】:Has no segue with identifier 'searchSegue' through xib file's class通过xib文件的类没有标识符'searchSegue'的segue
【发布时间】:2026-01-26 13:00:02
【问题描述】:

我正在使用 segue (searchSegue) 将 我的搜索屏幕 (SearchViewController) 连接到搜索结果页面 (PhotoStreamViewController)。

SearchViewController 是一个集合视图。每个集合视图单元格在 Xib 文件中都有一个设计。 (xib文件的类是SearchCategoryRowCell

目前,当我通过SearchViewController 触发searchSegue 时,它工作正常。但是每当我通过SearchCategoryRowCell 触发相同的转场时,我就会得到Has no segue with identifier 'searchSegue'

SearchViewController.swift

 class SearchViewController: UIViewController,UISearchBarDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    ...
   func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchRedirect(keyword: searchBar.text!)
    }


    func searchRedirect(keyword:String) {
        performSegue(withIdentifier: "searchSegue", sender:self)
        PhotoStreamViewController.searchString = keyword
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    ...
  }

SearchCategoryRowCell.swift

class SearchCategoryRowCell: UICollectionViewCell {
    //the method below is triggered by a click action  
    @objc func searchRedirection(_ sender:UIButton) {
        print("we")
        print(subCategoryArray[sender.tag].name)

        let searchViewcontroller = SearchViewController(nibName: "SearchViewController", bundle: nil)
        searchViewcontroller.searchRedirect(keyword: "otherSearchKeyword")

    }
   ...
}

【问题讨论】:

    标签: ios swift uicollectionview segue


    【解决方案1】:

    您已经完美地解释了原因。你是说:

    let searchViewcontroller = SearchViewController(nibName: "SearchViewController", bundle: nil)
    searchViewcontroller.searchRedirect(keyword: "otherSearchKeyword")
    

    所以searchViewcontroller 是在您的代码中实例化的全新视图控制器。因此,它没有segues。带有 segues 的视图控制器是 故事板中的一个,它是一个完全不同的视图控制器。

    【讨论】:

      【解决方案2】:

      这个

       let searchViewcontroller = SearchViewController(nibName: "SearchViewController", bundle: nil)
      

      不是当前呈现的 VC,你必须使用委托或将 self 声明为单元类中的属性

      class SearchCategoryRowCell: UICollectionViewCell {
        var sear:SearchViewController?
      
      }
      

      ans 将其设置在 SearchViewController 中的 cellForItem 中

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      
         let cell =  collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath) as! cellClassName
      
         cell.sear = self
      
         return cell;
      
       }
      

      //

      然后你可以使用呈现的对象

      @objc func searchRedirection(_ sender:UIButton) {
      
          print("we")
          print(subCategoryArray[sender.tag].name)
          sear?.searchRedirect(keyword: "otherSearchKeyword")
      
      }
      

      【讨论】:

      • 这是一个很好的解决方案。它工作得很好。你是救命稻草!
      • 快乐编码:)