UIImagePickerController

import UIKit

class ViewController: UIViewController,
    UIImagePickerControllerDelegate,
    UINavigationControllerDelegate
{

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBOutlet weak var imageView: UIImageView!
    
    @IBAction func butonPressed(_ sender: Any) {
//    let sourceType:UIImagePickerController.SourceType = .camera
//    let sourceType:UIImagePickerController.SourceType = .savedPhotosAlbum
        let sourceType:UIImagePickerController.SourceType = .photoLibrary
        
        if UIImagePickerController.isSourceTypeAvailable(
            UIImagePickerController.SourceType.photoLibrary){
            // UIImagePickerControllerを表示
            let imagePicker = UIImagePickerController()
            imagePicker.sourceType = sourceType
            imagePicker.delegate = self
            self.present(imagePicker, animated: true, completion: nil)
        }
        else{
            debugPrint("error")
        }
    }
    
    // 画像選択時に呼ばれる
    func imagePickerController(_ imagePicker: UIImagePickerController,
            didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){
        
        if let pickedImage = info[.originalImage]
            as? UIImage {
            
            imageView.contentMode = .scaleAspectFit
            imageView.image = pickedImage
        }

        //閉じる処理
        imagePicker.dismiss(animated: true, completion: nil)
    }
    
    // キャンセルされた時に呼ばれる
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
}
UIImagePickerControllerの Delegateとして、
UIImagePickerControllerDelegate,
UINavigationControllerDelegate
が必要。

カメラを使用する場合

   let sourceType:UIImagePickerController.SourceType = .camera

写真(Photo Library) から選択する場合

   let sourceType:UIImagePickerController.SourceType = .photoLibrary

モーメントから選択する場合

   let sourceType:UIImagePickerController.SourceType = .savedPhotosAlbum

投稿者: admin

Free Software Engineer

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です