LoginSignup
26
25

More than 5 years have passed since last update.

UIImagePickerControllerでフォトライブラリから画像を選ぶサンプル

Posted at

UIImagePickerControllerを使ってフォトライブラリから画像を選ぶサンプルプルグラムを書いてみました。
フォトライブラリから画像を選択するために、プロジェクトの info.plistにフォトライブラリを使用する旨を記述します。これを書いておかないとUIImagePickerControllerは使えません。
キーの値は以下の値を使います。TypeStringValueの中に使用理由を書きます。
使用理由を書かないと審査の時に落とされるらしいです。下の画像のような感じです。
スクリーンショット 2017-06-14 23.12.59.png

ViewController.swift

import UIKit

class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    var imagePickUpButton:UIButton = UIButton()
    var picker: UIImagePickerController! = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()

        //押されるとUIImagePickerControllerが開くボタンを作成する
        imagePickUpButton.frame = self.view.bounds
        imagePickUpButton.addTarget(self, action: #selector(imagePickUpButtonClicked(sender:)), for: .touchUpInside)
        imagePickUpButton.backgroundColor = UIColor.gray
        imagePickUpButton.setTitle("Toupe Me!!", for: UIControlState.normal)
        self.view.addSubview(imagePickUpButton)
    }

    //basicボタンが押されたら呼ばれます
    func imagePickUpButtonClicked(sender: UIButton){

        //PhotoLibraryから画像を選択
        picker.sourceType = UIImagePickerControllerSourceType.photoLibrary

        //デリゲートを設定する
        picker.delegate = self

        //現れるピッカーNavigationBarの文字色を設定する
        picker.navigationBar.tintColor = UIColor.white

        //現れるピッカーNavigationBarの背景色を設定する
        picker.navigationBar.barTintColor = UIColor.gray

        //ピッカーを表示する
        present(picker, animated: true, completion: nil)
    }

    //UIImagePickerControllerのデリゲートメソッド

    //画像が選択された時に呼ばれる.
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {

            //ボタンの背景に選択した画像を設定
            imagePickUpButton.setBackgroundImage(image, for: UIControlState.normal)
        } else{
            print("Error")
        }

        // モーダルビューを閉じる
        self.dismiss(animated: true, completion: nil)
    }

     //画像選択がキャンセルされた時に呼ばれる.
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

        // モーダルビューを閉じる
        self.dismiss(animated: true, completion: nil)
    }
}

実行すると以下のようになります

スクリーンショット 2017-06-15 0.06.59.png
スクリーンショット 2017-06-15 0.07.23.png

26
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
25