Jayprakash Dubey Jayprakash Dubey - 1 year ago 69
Swift Question

Swift 2.2 : Pass value between view controllers iOS

I'm trying to pass value between two view controller but it failed.
Second view controller (which is table view controller) is presented modally when button present in first view controller is pressed.

When user taps on any cell present in second view controller it is dismissed and value of cell is set to button present in first view controller.

Below is code that I've used :


class ForgotPasswordViewController: UIViewController {

var securityQuestion = ""

@IBOutlet weak var btnSecurityQuestion: UIButton!

//MARK: - viewDidLoad
override func viewDidLoad() {

var secQuestionAccessor: (String) {
return securityQuestion
}set(param) { print("param : \(param)") //Value is correctly printed in console
securityQuestion = param
print("securityQuestion : \(securityQuestion)") //Value is correctly printed in console

//MARK: - viewWillAppear
override func viewWillAppear(animated: Bool) {
. . .

print("secQuestionAccessor : \(secQuestionAccessor)") //Value is empty here

if secQuestionAccessor == "" {
btnSecurityQuestion.setTitle("Select", forState: UIControlState.Normal)
else {
btnSecurityQuestion.setTitle(secQuestionAccessor, forState: UIControlState.Normal)
. . .
. . .

SecurityQuestionViewController :

class SecurityQuestionViewController: UITableViewController {
. . .

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

let objForgotPassword = ForgotPasswordViewController()
print("\(responseQuestion.objectAtIndex(indexPath.row) as! String)") //Value printed correctly here
objForgotPassword.secQuestionAccessor = responseQuestion.objectAtIndex(indexPath.row) as! String
self.dismissViewControllerAnimated(true, completion: nil)
. . .

Screenshot 1

Where I'm going wrong? Any other solution?

This link helped in creating a delegate using Swift language.
However, the
app crashes when second view controller is presented using modal segue.

It crashes when delegate is declared weak and set to nil in second view controller. It works fine for show segue.

How can this be done using modal segue?

Answer Source

Add a protocol to your SecurityQuestionViewController with a function that accepts the data you want to pass to the previous viewController as a parameter. In your ForgotPasswordViewController implement that function. Before dismissing the SecurityQuestionViewController call that function on delegate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download