In the iOS Developer Library swift tutorial Connect the UI to Code chapter, there was something I didn't understand about delete, so I would like to ask you a question.
import UIKit
classViewController:UIViewController, UITextFieldDelegate{
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var mealNameLabel: UILabel!
override func viewDidLoad(){
super.viewDidLoad()
nameTextField.delegate=self
functextFieldShouldReturn(textField:UITextField) - >Bool{
textField.resignFirstResponder()
return true
}
functextFieldDidEndEditing (textField:UITextField) {
mealNameLabel.text=textField.text
}
@ IBAction funcsetDefaultLabelText (sender: UIButton) {
mealNameLabel.text="Default Text"
}
override funcdidReceiveMemoryWarning(){
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I understand that ViewController means delete text field.
nameTextField.delegate=self
So,
nameTextField.delegate=ViewController()
When I rewritten it, there was no error on the code, but the simulator did not change the label when I typed characters in the text field and pressed the return key.
What does this self refer to?
swift swift2 delegate
First, understand the relationship between classes and instances.
A class is just a design document, and an instance is like a robot built on that design document."Instantization" or "Create Instance" means that you are making a new robot.
Based on the above, what self
refers to is "the robot itself executing the instruction at that time."
nameTextField.delegate=self
The robot executing the command at that point sets itself as a delete.The robot has its own view that is displayed on the screen, and after the iOS system manufactures the robot, it needs an instance of @IBOutlet
(this is another robot, though of a different kind).I'm giving it to you.
However,
nameTextField.delegate=ViewController()
This is the same type of robot called ViewController
, but it is a completely different robot from the one currently in charge of displaying the screen.Unlike robots created by iOS, @IBOutlet
of robots created by designating the initializer directly does not automatically set anything.
Do you understand what's going on?
Some people find the "robot" metaphor rather difficult to understand.If you have any questions or concerns, please let us know in your comments.
601 GDB gets version error when attempting to debug with the Presense SDK (IDE)
897 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
611 Uncaught (inpromise) Error on Electron: An object could not be cloned
568 Who developed the "avformat-59.dll" that comes with FFmpeg?
© 2024 OneMinuteCode. All rights reserved.