从viewController发送字符串到另一个

时间:2016-12-15 16:44:58

标签: ios swift uiviewcontroller viewcontroller

请在将此问题标记为重复之前,我想知道为什么我的代码失败,而不是发送到另一个正在运行的代码。

我是swift的新手,我想发送变量" um_words" (单击按钮时计算)当单击相同按钮时从viewController中计算,将该变量保存在secondViewController中并在textView中显示。为此,我尝试了对此代码的许多修改,它在控制台中没有出错,但没有在textView上显示变量的值:

第一次VC

import UIKit
import Foundation

class TransViewController: UIViewController {

@IBOutlet var trad_text: UITextView!
@IBOutlet var buttonTrad: UIButton!
@IBOutlet var labelsitoh: UILabel!

var num_words = 0

@IBAction func butCalc(_ sender: UIButton) {

    let text = trad_text.text

    num_words =  (text?.components(separatedBy: " ").count)!-1

     func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        var DestViewController : PaymentViewController = segue.destination as! PaymentViewController

        DestViewController.num_words =  String(num_words)
    }

}


override func viewDidLoad() {
    super.viewDidLoad()

    trad_text!.layer.borderWidth = 1
    trad_text!.layer.cornerRadius = 20
    trad_text!.layer.borderColor = UIColor(red:0.22, green:0.26, blue:0.39, alpha:1.0).cgColor
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

}

第二个VC

import UIKit
import Foundation

class PaymentViewController: UIViewController {

@IBOutlet var labelImport: UITextView!

var num_words = String()

override func viewDidLoad() {
    super.viewDidLoad()

    labelImport.text = num_words

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

}

我有一个假设,为什么它不起作用:功能"准备"没有被召唤;它只在单击按钮时进入下一个VC ...

感谢您的时间。

2 个答案:

答案 0 :(得分:1)

请参阅:

IBAction func butCalc(_ sender: UIButton) {
    let text = trad_text.text
    num_words =  (text?.components(separatedBy: " ").count)!-1
    self.performSegue(withIdentifier: "yourSegueIdentifier", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "yourSegueIdentifier") {
        var destViewController : PaymentViewController = segue.destination as! PaymentViewController
        destViewController.num_words =  String(num_words)
    }
}

你已经在另一个功能中创建了一个功能...... 请试试这个。

PS:我没有测试这段代码

答案 1 :(得分:1)

func prepare应该在按钮动作之外,当触发segue时会调用它。

@IBAction func butCalc(_ sender: UIButton) {

    let text = trad_text.text

    num_words =  (text?.components(separatedBy: " ").count)!-1

}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    var DestViewController : PaymentViewController = segue.destination as! PaymentViewController

    DestViewController.num_words =  String(num_words)

}