Swift - 将文本和int从vc1传递到vc 2(uitextfield - > vc2中的标签)

时间:2015-06-20 16:46:33

标签: swift

在第二个VC作品中仅将文本字段中的输入文本传递给标签!!但我希望当uitextfield中的用户类型编号为10时,(1票是2欧元所以10票* 2欧元是20)当我点击PAY按钮时,所以SUM可以在第二个VC的标签中显示,我认为viewdidload in VC2正在准备之前发生,我不知道。当我第二次点击PAY按钮时它工作,但是当我第一次点击PAY按钮时标签显示为零,帮助:)嵌入导航控制器进行导航。

 1

VC1

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var howManyTickets: UITextField!

var sumTicketsAndPriceOfTickets = Int()
var priceOfTicket = 2 // euros

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

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


@IBAction func platiTeKarte(sender: AnyObject) {

    sumTicketsAndPriceOfTickets = howManyTickets.text.toInt()! * priceOfTicket

    }

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    let driver = segue.destinationViewController as! primaocViewController

    var whatToPass = sumTicketsAndPriceOfTickets

    driver.receiver = whatToPass
}
}

VC2

import UIKit

class primaocViewController: UIViewController {

@IBOutlet weak var displaySum: UILabel!

var receiver:Int!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    self.displaySum.text = String(receiver)

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

1 个答案:

答案 0 :(得分:0)

如果您的按钮直接连接到segue,那么您也不需要@IBAction。正如您所看到的,{@ 1}}发生在@IBAction for Pay按钮之前。只需在prepareForSegue中计算您的价值:

prepareForSegue

我更改了薪水的计算以使用 nil coalescing operator override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let driver = segue.destinationViewController as! primaocViewController driver.receiver = (howManyTickets.text.toInt() ?? 0) * priceOfTicket } 。这通常是一种更安全的方法,因为如果??因任何原因返回toInt(),则在这种情况下只会使用nil而不是崩溃。