我怎样才能返回到另一个视图控制器,然后转发到另一个视图控制器

How can I Segue back, to a different view controller, and then forward, to another view controller

我是第一次涉足 iOS 应用程序开发,我有一个项目,目前正在做布局。

基本上我有一个主视图控制器,还有其他的(为了清楚起见,我们将它们称为 VC1、VC2 等...)

应用程序启动到 VC1,您单击搜索按钮,会弹出一个模态 VC2,其中包含一个最近搜索栏和一个搜索栏。你输入一个名字并点击搜索,这基本上就是我希望它返回 VC1,然后转发到 VC3(应用程序的播放器屏幕)

现在是 VC1(SearchButtonAction) -> VC2(SearchPlayerAction) -> VC3(但是从模态到视图控制器的转换看起来很奇怪,如果我回击它看起来更奇怪。

我想要它去

VC1(SearchButtonAction) -> VC2(SearchPlayerAction) -> VC1 -> VC3

我真的不知道如何管理它,或者我会附上一些代码。相反,我附上了我目前所做工作的屏幕截图。

我不确定我是否应该做类似 prepareForSegue 的事情,并创建一个布尔值来标记它是否应该在加载时自动继续发送到 VC3,但是我需要通过数据到 VC1,只是为了将它传回 VC3,这看起来很乱,我只想将相同的数据从 VC2 转回 VC3,尽管要通过 VC1。我希望这很清楚 x.x

您可以使用几个选项。

1.放松 Segue

我最近开始使用这些,它们对于将数据从一个 VC 传回另一个非常有用。您基本上是在 VC 中添加一个函数,您将返回到该函数,在您的情况下,这将是 VC1。当您关闭 VC2 时,将调用 VC1 中的此函数。然后您可以从这里推送到 VC3。

我附上了一个简短的代码示例,但是 here is a link to a good tutorial that will describe it better.

示例

VC2

class ViewController2: UIViewController 
{
  let dataToPassToVC3 = "Hello"

  @IBAction func dismissButtonTapped(_ sender: Any) 
  {
    self.dismiss(animated: true, completion: nil)
  }
}

VC1

class ViewController1: UIViewController 
{
  @IBAction func unwindFromVC2(segue:UIStoryboardSegue) 
  {
    //Using the segue.source will give you the instance of ViewController2 you 
    //dismissed from. You can grab any data you need to pass to VC3 from here.

    let VC2 = segue.source as! ViewController2 
    VC3.dataNeeded = VC2.dataToPassToVC3

    self.present(VC3, animated: true, completion: nil)
  }
}

2。委托模式

VC2 可以创建一个 VC1 可以遵守的协议。在您关闭 VC2.

时调用此协议函数

示例

VC2

protocol ViewController2Delegate 
{
  func viewController2WillDismiss(with dataForVC3: String)
}

class ViewController2: UIViewController 
{
  @IBAction func dismissButtonTapped(_ sender: Any) 
  {
    delegate?.viewController2WillDismiss(with: "Hello")
    self.dismiss(animated: true, completion: nil)
  }
}

VC1

class ViewController1: UIViewController, ViewController2Delegate 
{
  func viewController2WillDismiss(with dataForVC3: String) 
  {
    VC3.dataNeeded = dataForVC3 
    self.present(VC3, animated: true, completion: nil)
  }
}