如何将数据从ViewDidLoad传递到按钮的功能

时间:2019-07-15 15:02:19

标签: ios swift xcode

我在ViewDidLoad中生成了两个随机数。我要加上这两个数字,结果应在带有输入字段数据的按钮中检查。我的问题是我不知道如何将结果传输到功能CheckResultBtn中。现在无法识别结果。

这是我的代码,我非常感谢任何帮助

 class ViewController: UIViewController {



    @IBOutlet weak var lblRandomNumOne: UILabel!
    @IBOutlet weak var lblRandomNumTwo: UILabel!
    @IBOutlet weak var KidsField: UITextField!
    @IBOutlet weak var Showresult: UILabel!
    @IBOutlet weak var CheckResult: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        let x = Int.random(in: 0 ..< 10)
        lblRandomNumOne.text = String(x);


        let y = Int.random(in: 0 ..< 10)
        lblRandomNumTwo.text = String(y);

        let result = x + y;  
        CheckResultBtn(result) //not sure about this 


       }


    @IBAction func CheckResultBtn(_ sender: Any)
    {

        if (KidsField != nil)
        {
            let kidsresult = Int(KidsField.text!) ;

            if (result == kidsresult)
            {

                Showresult.text = "Bravo";

            }
            else
            {
                Showresult.text = "Try Again!"
            }

        }
    }



}

3 个答案:

答案 0 :(得分:1)

在viewDidload函数之前声明变量“结果”

var result : Int!

然后继续对viewDidload中的变量执行操作,即可摆脱这一行

CheckResultBtn(result) 

并且您应该能够访问IBAction函数中的结果变量

答案 1 :(得分:0)

您可以尝试

@IBAction func checkResultBtn(_ sender: Any)  {   
   displayRes(Int(kidsField.text!)!)
}  
func displayRes(_ result:Int)    {  
   showresult.text = result == kidsresult ? "Bravo" : "Try Again!" 
}

然后在viewDidLoad

displayRes(x+y)         

答案 2 :(得分:-1)

创建一个新函数,而不是使用action方法 像这样:

func CheckResultBtn(_ result : Int) {

        if (KidsField != nil)
        {
            let kidsresult = Int(KidsField.text!) ;

            if (result == kidsresult)
            {

                Showresult.text = "Bravo";

            }
            else
            {
                Showresult.text = "Try Again!"
            }

        }
    }

或创建一个变量

var result : Int?

分配一个值         结果= x + y;

并在操作方法内部使用

var result : Int?
override func viewDidLoad() {
    super.viewDidLoad()

    let x = Int.random(in: 0 ..< 10)
    lblRandomNumOne.text = String(x);


    let y = Int.random(in: 0 ..< 10)
    lblRandomNumTwo.text = String(y);

    result = x + y;
}


@IBAction func CheckResultBtn(_ sender: Any) {
    if (KidsField != nil)
    {
        let kidsresult = Int(KidsField.text!) ;

        if (result == kidsresult)
        {

            Showresult.text = "Bravo";

        }
        else
        {
            Showresult.text = "Try Again!"
        }

    }
}