How to allow user to pick the image with Swift?

后端 未结 21 806
[愿得一人]
[愿得一人] 2020-12-02 06:01

I am writing my first iOS application (iPhone only) with Swift. The main application view should allow user to choose the image from the photo gallery.

I\'ve found

21条回答
  •  温柔的废话
    2020-12-02 06:29

    here is an easy way to do it:

    but first you have to add ( Privacy - Photo Library Usage Description ) in the info.plist, and you should have a button and a UIImageView in your viewController.

    then create an outlet of the UIImageView ( in this code the outlet is called myImage), and an action of the button ( I called the action importing in my code )

    import UIKit
    class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
        }
        @IBOutlet weak var myImage: UIImageView!
        @IBAction func importing(_ sender: Any) {
            let Picker = UIImagePickerController()
            Picker.delegate = self
            Picker.sourceType = .photoLibrary
            self.present(Picker, animated: true, completion: nil)
            Picker.allowsEditing = true
            Picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
        }
    
         func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any])
        {
            let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //1
            myImage.contentMode = .scaleAspectFit //2
            myImage.image = chosenImage //3
            dismiss(animated:true, completion: nil) //4
        }
    
    }
    

提交回复
热议问题