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

时间:2018-05-23 09:09:11

标签: ios swift uiimagepickercontroller

我是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中设置所选图片。有用。我打开galery,我选择一个图像,然后转换回图像集的视图。但是,它为什么有效?我从不调用函数imagePickerController。与之前使用的语言相比,我应该在PhotoLibrary中点击选择按钮调用此函数。喜欢某事或某事。但是在这里它只是通过定义函数自动调用。那是为什么?

2 个答案:

答案 0 :(得分:3)

imagePicker.delegate = self

转换为:"嘿imagePicker,当发生某些事情时,请通过调用我的UIImagePickerControllerDelegate方法告诉我们!"

特别是,正在调用imagePickerController(_:didFinishPickingMediaWithInfo:)的实现,这是UIImagePickerControllerDelegate协议的一部分。

答案 1 :(得分:1)

委托模式

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

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

此模式经常在iOS开发中使用。 有关委派模式的更多信息,请参阅in Apple's documentation