简体   繁体   中英

Objective-C : UIViewController get Data from ContainerView

This is my first time working with container views.

In my app's LoginViewController, I am using a container view which embeds a UITableViewController with two static cells which contain UITextFields for email and password.

When a user presses 'Login' button on LoginViewController, how can this class get the information from the UITableViewController embedded inside the container view?

You can capture the login form view controller in the prepareForSegue(segue:sender:) since container views trigger an embedded segue to the child View Controller. Then have the login form View Controller expose the email and passwords. The code below is in Swift, but there isn't anything magically Swifty about it. It's just easier to demonstrate what I mean.

class LogInViewController : UIViewController {
   var logInForm : LogInFormViewController?
   override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
       if let child = segue.destinationViewController as? LogInFormViewController {
           logInForm = child
       }
   }
   @IBOutlet func logIn(sender: AnyObject?) {
       sendLogIn(logInForm?.email, logInForm?.password)
   }
}
class LogInFormTableViewController : UITableViewController {
    var email:String { get { return _emailField.text } }
    var password:String { get { return _passwordField.text } }
}

This can be extended to handle the enable/disable of the login button based on the form values if you need to.

To flip it and call back out the parent, like the comments discussion is talking about, use a protocol on the parent and attach it to the form during the perform segue action, just like above.

protocol LogInDelegate {
   func logIn(email:String, _ password:String)
}
class LogInViewController :UIViewController, LogInDelegate {
   override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
       if let child = segue.destinationViewController as? LogInFormViewController {
           child.logInDelegate = self
       }
   }
   func logIn(email: String, _ password:String) {
   }
}
class LogInFormTableViewController: UITableViewController {
    var logInDelegate: LogInDelegate?
   @IBOutlet func logIn(sender: AnyObject?) {
       logInDelegate?.logIn(_emailField.text, _passwordField.text)
   }
}
  1. You can create a delegate(Protocol) to call back
  2. You can use NSNotification
  3. You can write a lightweight call back block
  4. I believe for the containerView and its childView, there is a property called parentViewController which you can refer to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM