iOS Swift imagePickerController无法调用

时间:2018-07-23 02:53:27

标签: ios swift uiimagepickercontroller

class MyPage: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    var imagePicker = UIImagePickerController()
    @IBOutlet weak var selectImage: UIButton!

    override func viewDidLoad() {
        imagePicker.sourceType = .photoLibrary
        imagePicker.delegate = self
    }



   @IBAction func selectImage(_ sender: Any) {
            print("a")
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
                print("b")
                imagePicker.allowsEditing = false
                imagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
                self.present(imagePicker, animated: true,completion: nil)
            }
    @objc func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
            self.dismiss(animated: true, completion: { () -> Void in
                print("dismiss")
            })

            print(image)
            selectImage.setImage(image, for: .normal)
        }
}

如果触摸按钮,则打印a和b并弹出photoLibrary

但选择照片不拨打电话imagePickerController

选择照片后不执行任何操作

如何在Swift 4中使用图像选择器?

2 个答案:

答案 0 :(得分:1)

@objc方法和Delegate方法中删除delegate是这个,所以用下面的命令替换函数:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])

并使用此图像获取图片:

guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {return}

答案 1 :(得分:-1)

import UIKit

ViewController类:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

let imageView = UIImageView()
let imagepicker = UIImagePickerController()
override func viewDidLoad() {
    super.viewDidLoad()
    self.imagepicker.delegate = self
    imageView.frame = CGRect(x: 40, y: 150, width: 100, height: 100)
    self.view.addSubview(imageView)
}

@IBAction func uploadImage(_ sender : UIButton) {
    imagepicker.cameraDevice = .rear
    imagepicker.cameraCaptureMode = .photo
    imagepicker.sourceType = .photoLibrary
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
        return
    }
    imageView.image = image
    print(image)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    self.dismiss(animated: true, completion: nil)
}

}