2015-06-20 68 views
0

僅傳遞文本字段中的輸入文本以標記第二個VC作品!但我想當用戶在uitextfield中輸入數字10時(1張票是2歐元,所以10票* 2歐元是20),當我點擊PAY按鈕時,SUM可以在第二個VC中顯示標籤,我認爲viewdidload在在prepareForSegue之前,VC2正在發生,我不知道。它工作時,我點擊第二次付費按鈕,但不是當我第一次點擊按鈕,其中標籤顯示爲零,幫助:)嵌入導航控制器中的導航。Swift - 將文本和int從vc1傳遞給vc 2(uitextfield - > vc2中的標籤)

 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. 
} 

} 

回答

0

如果您的按鈕直接連接到一個SEGUE,那麼你就需要一個@IBAction爲好。正如您所看到的,prepareForSegue發生在您的付款按鈕的@IBAction之前。就在prepareForSegue計算你的價值:

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

    let driver = segue.destinationViewController as! primaocViewController 

    driver.receiver = (howManyTickets.text.toInt() ?? 0) * priceOfTicket 
} 

我改變了薪酬計算使用零合併運算??。這通常是一種更安全的方法,因爲如果toInt()由於任何原因返回nil,則在這種情況下僅使用0而不是崩潰。

+0

謝謝你,甚至更簡單:),或者我可以將第10張門票傳給第二個VC並在那裏計算,..再次感謝!編輯:它的工作原理也driver.receiver =(howManyTickets.text.toInt())! * priceOfTicket – Igy

相關問題