xcode 2016年4月27日 星期三
Connect the UI to Code
主题
- The weak keyword means that it’s possible for that property to have no value (be nil) at some point in its life.
- @IBOutlet weak var nameTextField: !
- an implicitly unwrapped optional, which is an optional type that will always have a value after the value is first set.
Target-action is a design in which one object sends a message to another object when a specific event occurs.
Create Outlets for UI Elements
To connect the text field to the ViewController.swift code
A delegate is an object that acts on behalf of, or in coordination with, another object.
any object can serve as a delegate for another object as long as it conforms to the appropriate protocol.
because ViewController keeps a reference to the text field, you’ll make ViewController the text field’s delegate.
class ViewController: a href="" UIViewController /a , a href="" UITextFieldDelegate /a {
By adopting the protocol, you gave the ViewController class the ability to identify itself as a UITextFieldDelegate. This means you can set it as the delegate of the text field and implement some of its behavior to handle the text field’s user input.
To set ViewController as the delegate for nameTextField
// Handle the text field’s user input through delegate callbacks.
nameTextField.delegate = self
The UITextFieldDelegate protocol contains optional methods, which means that you’re not required to implement them.
When the user taps a text field, it automatically becomes first responder. In an app, the first responder is an object that is first on the line for receiving many kinds of app events, including key events, motion events, and action messages, among others. In other words, many of the events generated by the user are initially routed to the first responder.
As a result of the text field becoming first responder, iOS displays the keyboard and begins an editing session for that text field. What a user types using that keyboard gets inserted into the text field.
When a user wants to finish editing the text field, the text field needs to resign its first-responder status. Because the text field will no longer be the active object in the app, events need to get routed to a more appropriate object.
This is where your implementation of UITextFieldDelegate methods comes in. You need to specify that the text field should resign its first-responder status when the user taps a button to end editing in the text field. You do this in the textFieldShouldReturn(_:) method, which gets called when the user taps Return (or in this case, Done) on the keyboard.
To implement the UITextFieldDelegate protocol method textFieldShouldReturn(_:)