iPhoneアプリ開発 カメラロールの画像をUIImageViewに表示する
MacBookにてiPhoneアプリ開発を勉強し始めて2週間ほど。
UIImageViewにカメラロールで選択した画像を表示するコードを書くのに1週間を費やしました。
他の言語に比べてswiftのサンプルはネット上に少ないんですね。すごく苦労したので載せておきます。
バージョン情報
Swift4
Xcode10
SettingViewControlllerクラスというを作成し、その中に色々実装していきます。
StoryBoardでUIImageViewとButtonを設定したViewControllerとSettingViewControlllerクラスを結びつけておきます。
また、UIImageViewはOutlet接続、ButtonはAction接続で、SettingViewControlllerクラスにconectしておきます。
@IBOutlet weak var facePicture: UIImageView! @IBAction func setButton(_ sender: UIButton) { toCameraRoll() }
SettingViewControlllerクラスに色々実装していきます。
import UIKit import AssetsLibrary import Photos class SettingViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { }
ボタン押した時にtoCameraRoll()を呼んでいるので、toCameraRoll()のなかにカメラロールにアクセスするコードを実装します。
@IBAction func toCameraRoll(){ if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) { let picker = UIImagePickerController() picker.allowsEditing = false picker.sourceType = .photoLibrary picker.delegate = self self.present(picker, animated: true, completion: nil) } }
上記を実行するとカメラロールから画像を選択できます。
画像を選択すると、”imagePickerContriller”が呼ばれるので、以下を実装しておきます。
//写真が選択された時の処理 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { //選択された画像を保存 if let picker = info[.originalImage] as? UIImage { //画像を設定 smileFacePicture.image = picker } //写真ライブラリを閉じる dismiss(animated: true, completion: nil) }
以上!