在 Swift 中将变量从一个 ViewController 传递到另一个 [英] Pass variables from one ViewController to another in Swift

查看:35
本文介绍了在 Swift 中将变量从一个 ViewController 传递到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个计算器类,第一个 ViewController 用于插入值,第二个 ViewController 用于显示计算结果.不幸的是,如果我单击按钮,我会收到一个名为无法解开 Optional.None"的错误.我知道语法有问题,但我不知道如何改进.

I have a calculator class, a first ViewController to insert the values and a second ViewController to show the result of the calculation. Unfortunately I get a error called "Can't unwrap Optional.None" if I click the button. I know it's something wrong with the syntax, but I don't know how to improve it.

故事板中第一个 ViewController 中的按钮设置为Segue: Show (e.g. Push)",如果他被点击,则切换到 secondViewController.

The button in the first Viewcontroller is set to "Segue: Show (e.g. Push)" in the storyboard to switch to the secondViewController if he gets tapped.

计算器类类似于:

class Calculator: NSObject {

    func calculate (a:Int,b:Int) -> (Int) {
        var result = a * b
        return (result)
    }
}

Viewcontroller 调用函数,插入 a/b 并想更改位于 secondviewcontroller 中的标签:

The Viewcontroller calls the function, inserts a/b and wants to change the label which is located in the secondviewcontroller:

class ViewController: UIViewController {

@IBAction func myButtonPressed(sender : AnyObject) {
    showResult()
}

var numberOne = 4
var numberTwo = 7

var myCalc = Calculator()

func showResult () {
    var myResult = myCalc.calculate(numberOne, b: numberTwo)
    println("myResult is \(String(myResult))")
    var myVC = secondViewController()
    myVC.setResultLabel(myResult)
}

这里是secondViewController的代码

And here is the code of the secondViewController

class secondViewController: UIViewController {

@IBOutlet var myResultLabel : UILabel = nil

func setResultLabel (resultValue:Int) {
    myResultLabel.text = String(resultValue)
}

init(coder aDecoder: NSCoder!)
{
    super.init(coder: aDecoder)
}

推荐答案

在 Swift 中,默认情况下一切都是公开的.在类之外定义变量:

In Swift, everything is public by default. Define your variables outside the classes:

import UIKit

var placesArray: NSMutableArray!

class FirstViewController: UIViewController {
//
..
//
}

然后访问它

import UIKit

class TableViewController: UITableViewController {
//
placesArray = [1, 2, 3]
//
}

这篇关于在 Swift 中将变量从一个 ViewController 传递到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆