问题
I cannot understand what Delegates are used for in swift
I tried to search in any possible site what a delegate is and for what it is used for but I cannot completely grasp the meaning of them.
f.e. in this code
extension SignUpViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
}
}
what are the delegates assigned to the ViewController supposed to do? and how can I understand how to use them?
回答1:
I like to think with an analogy:
There will be a "speaker" and a "listener".
UIImagePickerController is already configured to "speak" when events happen, so when something like didFinishPickingMediaWithInfo happens, it "speaks" .
In your scenario, the UIViewController should be the "listener", this is configured with:
picker.delegate = self, assuming UIViewController implements UIImagePickerControllerDelegate.
In other words, make the UIViewController the "listener" for when the picker "speak".
And everything that the picker "speak", will be "listened" via UIImagePickerControllerDelegate by whoever is "listening".
Note: This is very superficial and abstract, of course it goes much beyond this, but I'm considering the OP situation.
回答2:
A delgate is a connection between 2 data types commonly vcs , that enable 1 of them to send data to the other by calling a method from the protocol that the receiver is conforming to in you example you set
let picker = UIImagePickerController()
picker.delegate = self // connection here
above receiver is SignUpViewController instance and sender is UIImagePickerController instance after the user picks a photo/video the picker calls didFinishPickingMediaWithInfo which is 1 of the UIImagePickerControllerDelegate methods , this what happens under the hood of
class UIImagePickerController { // look for it in framework visible part
weak var delegate:UIImagePickerControllerDelegate?
....
delegate?.imagePickerController(self,didFinishPickingMediaWithInfo:info)
}
来源:https://stackoverflow.com/questions/56719604/i-cannot-understand-what-delegates-are-about