我如何判断 swift 4 中哪个按钮调用了另一个视图?

How do I tell which button called another view in swift 4?

我想知道哪个按钮称为第二个视图,它显示了项目类型的列表。 tableViewCell 包含所有项目的数组。例如,如果用户点击汉堡,他将获得所有汉堡项目的列表。我已将每个按钮分别连接到第二个视图,但似乎必须有更好的方法,比如将它连接到所有按钮都连接到的 touchButton 方法,但我不确定如何执行此操作。另外,项目数组应该在 tableViewController 中还是 tableViewCell 中?

首先,我建议您只使用一个 segue,而不是为同一视图提供每个按钮 segue。

一种方法是根据项目 table 视图中的逻辑简单地使用指示符 int 或字符串,并通过获取 destinationVC 相应地分配它以准备 segue 方法。并在加载时处理列表项视图上的指示器。 (在这种方法中,您只有一个 segue,您将能够执行这项工作)。

就 table 视图方法而言。对项目列表使用 tableview,对单个项目使用 tableViewCell。

理论上:

如果您要从 current 转到下一个 ViewController ,您可以在下一个 View Controller 中创建一个变量在从当前 VC 移动到下一个时,您可以在 @IBAction 方法中获取 Button 的名称并创建下一个 VC 的实例和访问 variable(之前创建的)并将该按钮的名称分配给 variable

代码:

class CurrentViewController: UIViewController {

  // Your other code goes here

  @IBAction func actionButtonTapped(_ sender: UIButton) {

     // Here we fetch the name of the button tapped
     let nameOfButtonTapped = sender.titleLabel!.text

     // Here we create instance of NextViewController
     let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "#yourNextVCIdentifierHere") as! NextViewController

     // Here we assign the name of the button tapped to the variable of NextViewController so we can access it there
     nextVC.buttonNameThatWasClicked = nameOfButtonTapped

     self.present(nextVC, animated: true, completion: nil)

   }
}

class NextViewController: UIViewController {

  var buttonNameThatWasClicked: String?

  override func viewDidLoad() {
   super.viewDidLoad()

   print(buttonNameThatWasClicked!)

  }

}

在这里,我们可以将所有按钮连接到一个@IBAction,方法是按住Control键拖动所有按钮到@IBAction方法的名称