Swift 2.2:视图控制器iOS之间传递值

Jay*_*bey 0 xcode storyboard ios segue swift

我试图在两个视图控制器之间传递值,但它失败了.当按下第一视图控制器中的按钮时 ,第二视图控制器(其为表视图控制器)以模态呈现.

当用户点击第二视图控制器中存在的任何单元格时,它被解除,并且单元格的值被设置为第一视图控制器中存在的按钮.

以下是我用过的代码:

ForgotPasswordViewController

class ForgotPasswordViewController: UIViewController {

    var securityQuestion = ""

    @IBOutlet weak var btnSecurityQuestion: UIButton!

    //MARK: - viewDidLoad
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    var secQuestionAccessor: (String) {
        get{
            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)
        }
        . . .
    }
  . . .
}
Run Code Online (Sandbox Code Playgroud)

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)
    }
  . . .
}
Run Code Online (Sandbox Code Playgroud)

截图1

我哪里错了?还有其他方法吗?

链接有助于使用Swift语言创建委托. 然而app crashes when second view controller is presented using modal segue.

在委托声明薄弱,设置在第二视图控制器零崩溃.它适用于show segue.

如何使用模态segue完成?

Max*_*ner 5

SecurityQuestionViewController使用一个函数为您的协议添加一个协议,该函数接受您想要传递给前一个viewController的数据作为参数.在你的ForgotPasswordViewController工具中那个功能.在解除SecurityQuestionViewController委托上的函数调用之前.