Reputation: 11
In my first view controller I have a function that is caller by the press of a button.
func BuyButton(sender:UIButton) {
print("clicked cell is at row \(sender.tag)")
let indexPath = NSIndexPath(row: sender.tag, section: 0)
let currentCell = tableView.cellForRow(at: indexPath as IndexPath) as! CustomCell
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let PaymentController = Storyboard.instantiateViewController(withIdentifier: "PaymentViewController") as! PaymentViewController
print(currentCell.Test.text!) //prints fine here
PaymentController.RecordTitle = currentCell.Test.text!
performSegue(withIdentifier: "Buy", sender: self)
}
In my payment view controller I define the variable as
var RecordTitle = String()
In my view did load of my Payment View Controller I try to print the RecordTitle and nothing prints
print(RecordTitle)//Nothing prints in payment view controller
What am I doing wrong? I have tried multiple methods and none seem to work.
Upvotes: 1
Views: 55
Reputation: 2259
You need to override prepare(segue, sender)
method and in that method get needed view controller and set title
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Buy" {
let vc = segue.destination as! PaymentViewController
vc.RecordTitle = sender as? String
}
}
Also don't forget to call performSegue
with that title
performSegue(withIdentifier: "Buy", sender: currentCell.Test.text!)
Upvotes: 1
Reputation: 1745
You can change viewController by 2 method: 1: instantiateViewController 2: performSegue but you are combining them if you want to use first method just do like this:
func BuyButton(sender:UIButton) {
print("clicked cell is at row \(sender.tag)")
let indexPath = NSIndexPath(row: sender.tag, section: 0)
let currentCell = tableView.cellForRow(at: indexPath as IndexPath) as! CustomCell
let Storyboard = UIStoryboard(name: "Main", bundle: nil)
let PaymentController = Storyboard.instantiateViewController(withIdentifier: "PaymentViewController") as! PaymentViewController
print(currentCell.Test.text!) //prints fine here
PaymentController.RecordTitle = currentCell.Test.text!
self.presentViewController(PaymentController, animated: false, completion: nil)
}
if you are interested in second method, there is a good example in this link: http://www.codingexplorer.com/segue-swift-view-controllers/
Upvotes: 2