如何以编程方式编写函数(对于续集:UIStoryboardSeque,发件人:任何?)

时间:2018-11-23 04:53:44

标签: swift segue programmatically

使用情节提要时,我具有以下代码:

 override func prepare (for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == ProfilePhotoViewController.identifier {
      guard let username = usernameTextField.text, let email = emailTextField.text, let password = passwordTextField.text else { return }

      let profilePhotoVC = segue.destination as! ProfilePhotoViewController
      profilePhotoVC.email = email
      profilePhotoVC.username = username
      profilePhotoVC.password = password
    }
  }

如果我不使用情节提要,而是以编程方式编写它们,以便将信息从当前控制器传递到ProfilePhotoViewController,我该如何编写这些代码?

编辑: 经过研究后,我了解以编程方式通过委托进行此操作。但是,我不知道如何完成代码:

需要从SignUpController ---> profilePhotoViewController传递用户名,电子邮件和密码

在SignUpController中:

协议SignUpControllerDelegate {      func handleSignUp(//我应该在这里写什么?) }

var委托:SignUpControllerDelegate?

@objc func handleSignUp(){

// ...其他代码..//

delegate?.handleSignUp(// ??) }

在ProfileViewController中:

我应该怎么写才能从SignUpController接收用户名,电子邮件和密码信息?

2 个答案:

答案 0 :(得分:2)

我们可以创建带有/不带有NIB文件的视图控制器。

对于NIB,您使用init(nibName: String?, bundle: Bundle?)方法。在这种情况下,view将使用Interface Builder定义。

// bundle = nil denote the main bundle
let viewController = MyViewController(nibName:"MyViewController", bundle: nil)

您还可以定义一个没有NIB文件的自定义UIViewController子类,并实现loadView()方法。

override func loadView() {
    self.view = UIView(...)
}

之后,我们需要将视图添加到视图层次结构中。

self.view.addSubview(viewController.view);
// or
self.present(viewController, animated: false, completion: nil)
// or if we have UINavigationController
self.navigationController?.pushViewController(viewController, animated: false)

答案 1 :(得分:-1)

尝试这样

guard let username = usernameTextField.text, let email = emailTextField.text, let password = passwordTextField.text else { return }

let profileVC = ProfilePhotoViewController()
profileVC.email = email