How to allow the user to pick a photo from his camera roll or photo library?

后端 未结 7 1537
粉色の甜心
粉色の甜心 2021-01-02 01:11

I\'m making a little photo editing app for fun. Users must select a photo from their camera roll which will then be imported for modification.

How does this generall

相关标签:
7条回答
  • 2021-01-02 02:10

    @WilliamT 's answer worked really well for me. Here is his, but updated for Swift 4 in case anyone is still looking for this.

    This goes into the view controller class block that contains the button that you want to trigger the camera/image picker.

    @IBAction func YourButtonToTriggerCamera/ImagePicker(_ sender: UIButton) {
        let picker = UIImagePickerController()
        picker.delegate = (self as UIImagePickerControllerDelegate & UINavigationControllerDelegate)
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {
            action in
            picker.sourceType = .camera
            self.present(picker, animated: true, completion: nil)
        }))
        alert.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: {
            action in
            picker.sourceType = .photoLibrary
            self.present(picker, animated: true, completion: nil)
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        self.present(alert, animated: true, completion: nil)
    }
    

    This goes below your View Controller Class:

    extension YourViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
        func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
            //use image here!
            dismiss(animated: true, completion: nil)
        }
    
        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            dismiss(animated: true, completion: nil)
        }
    }
    
    0 讨论(0)
提交回复
热议问题