如何从动态创建的故事板属性为nil

时间:2016-05-13 12:04:22

标签: ios swift uiviewcontroller segue uisearchcontroller

我正在开发一个具有搜索功能的项目。我有3个视图控制器,即HomeViewController,SearchResultViewController和DetailViewController。

在主页面上,我在navigationBar中搜索栏(使用UISearchController)以及一些虚拟内容。这里重要的是我使用单独的控制器(在我的例子中是SearchResultController)来显示结果。这个SearchResultController实际上是TableViewController的子类,它在tableview中显示结果。一切都很好,直到这里。

问题

现在,当我从结果中选择任何行时(即在SearchResultViewController),我想打开另一个视图控制器(DetailViewController),我将在其中显示有关此选定项目的详细信息。这是一件非常简单的事情,但我被困在这里。

好的,继续问题我已经实现了didSelectRowAtIndexPath方法,并且我正在调用performSegueWithIdentifier并且我收到错误“ Receiver没有带标识符的segue ”,因为storyboard属性为nil (文档中提到了这一点。)

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("storyboard property is \(self.storyboard)")
        performSegueWithIdentifier(segueIdentifier, sender: indexPath.row)
    }

注意: segueIdentifier与故事板上的相同。 我得到的故事板属性是零。

我想

当我点击搜索栏时,iOS会在内部创建并加载SearchResultController的实例以显示结果,因此其storyboard属性为nil,因此我收到了上述错误。

有人可以解决这个问题或任何指向正确方向的指针。

1 个答案:

答案 0 :(得分:2)

如果您以编程方式创建viewcontroller,那么您应该按下导航控制器,如

  UIViewController *vc = [[UIViewController alloc]init]; //your viewcontroller here

[self.navigationController pushViewController:vc animated:YES];

//or if you want to present it then

[self presentViewController:vc animated:YES completion:nil];

你不能执行segue,因为没有故事板没有segue

swift

中有类似的东西
 let vc: UIViewController = UIViewController()
    //your viewcontroller here
    self.navigationController!.pushViewController(vc, animated: true)
    //or if you want to present it then
    self.presentViewController(vc, animated: true, completion: { _ in })

迅速避免任何错误!!!

希望这会有所帮助:)