函数已创建,但从未调用过,但仍会执行

Function created, but never called, yet it is still executed

我是 iOS 开发和 Swift 的新手,如果这是一个微不足道的问题,我深表歉意。我有以下代码

import UIKit

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    var imagePicker: UIImagePickerController!

    @IBOutlet weak var imageView: UIImageView!

    @IBAction func openGalery(_ sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary;
            imagePicker.allowsEditing = true
            present(imagePicker, animated: true, completion: nil)
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        imagePicker.dismiss(animated: true, completion: nil)
        imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

在我创建的代码中 func imagePickerControllerimagePickerController 负责在 imageView 中设置 selected 图像。有用。我打开画廊,我 select 一个图像,然后有一个转换回到带有图像集的视图。但是,为什么它有效?我从不调用函数 imagePickerController。将此与我之前使用的语言进行比较,我应该在点击 PhotoLibrary 中的 select 按钮时调用此函数。比如一个事件什么的。但在这里它只是通过定义函数以某种方式自动调用。这是为什么?

imagePicker.delegate = self

转换为:"Hey imagePicker, when something happens, let me know by calling my UIImagePickerControllerDelegate methods!"

特别是您对 imagePickerController(_:didFinishPickingMediaWithInfo:) is being called, which is part of the UIImagePickerControllerDelegate 协议的实施。

这是委派模式

当您将 imagePicker 的委托设置为 self 时,您将开始从选择器接收事件。

protocol 中定义的事件。在这种情况下是 UIImagePickerControllerDelegate

此模式在 iOS 开发中经常使用。 有关委托模式的更多信息,您可以阅读 in Apple's documentation