简体   繁体   English

在Swift中页面视图控制器内的视图控制器之间传递数据

[英]Passing data between view controllers inside page view controllers in Swift

Sorry if this particular problem has been asked about, I followed the answers on other threads but none of them seemed to work, but I just started learning Swift so all of this is pretty new to me. 抱歉,如果有人问过这个特殊问题,我在其他线程上遵循了答案,但是似乎都没有用,但是我刚刚开始学习Swift,所以对我来说所有这些都是很新的。

So, I have a text field in two View Controllers and I want the third View Control to display a result based on the input from the other two controllers when I press a button. 因此,我在两个View Controller中都有一个文本字段,我希望第三个View Control在按下按钮时根据来自其他两个控制器的输入显示结果。

I followed this tutorial and placed the text fields, label and button like I said before. 我按照本教程进行操作 ,并像我之前所说的那样放置了文本字段,标签和按钮。 I placed my code (which you can see below) inside ViewControl.swift. 我将代码(您可以在下面看到)放置在ViewControl.swift中。

The problem is that when I attempt to run it I get a "Thread 1 :EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" error in the last two lines. 问题是,当我尝试运行它时,在最后两行中出现“线程1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)”错误。

class ViewController: UIViewController {

var a: String = ""
var b: String = ""

@IBOutlet weak var aTextField: UITextField!
@IBOutlet weak var bTextField: UITextField!
@IBOutlet weak var calculateButton: UIButton!
@IBOutlet weak var resultLabel: UILabel!

@IBAction func calculateButtonPressed(_ sender: UIButton) {
    let a = aTextField.text!;  
    let b = bTextField.text!;

I think that the error is from the data not passing between the views (because before I had everything in the same view and it worked fine), but since I only have one ViewController.swift file I couldn't figure out how to use a Segue. 我认为错误是由于数据没有在视图之间传递(因为在同一视图中所有数据都可以正常工作之前),但是由于我只有一个ViewController.swift文件,所以我不知道该如何使用Segue公司。

Do not declare same variables multiple times. 不要多次声明相同的变量。 Remove let before a & b . ab之前删除let You have already declared a & b globally and then tried to redeclare it inside IBAction 您已经在全局中声明ab ,然后尝试在IBAction重新声明它

class ViewController: UIViewController {

var a: String = ""
var b: String = ""

@IBOutlet weak var aTextField: UITextField!
@IBOutlet weak var bTextField: UITextField!
@IBOutlet weak var calculateButton: UIButton!
@IBOutlet weak var resultLabel: UILabel!

@IBAction func calculateButtonPressed(_ sender: UIButton) {
     a = aTextField.text!;  
     b = bTextField.text!;
  1. Make sure your control outlets are setted properly. 确保控制插座的设置正确。
  2. In your two variables a & b are re-declared.Just update your code like below 在您的两个变量中,a和b被重新声明。只需如下更新代码
 @IBAction func calculateButtonPressed(_ sender: UIButton) { self.a = aTextField.text! self.b = bTextField.text! } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM