##サンプル
カメラロール開く → 新規画面に選択した写真表示 → 閉じる という流れ。
##コード
ViewController.swift
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func toAlbum(){
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
let picker = UIImagePickerController()
picker.sourceType = .photoLibrary
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let nextView = storyboard.instantiateViewController(withIdentifier: "Photo") as! PhotoViewController
nextView.image = image
self.dismiss(animated: false)
present(nextView, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
PhotoViewController.swift
import UIKit
class PhotoViewController: UIViewController {
var image: UIImage?
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
imageView.image = image
imageView.contentMode = UIViewContentMode.scaleAspectFit
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func closeModal() {
imageView.image = nil
self.dismiss(animated: true, completion: nil)
}
}
Storyboardで各ViewControllerのidentifierにMain
とPhoto
を設定するのを忘れないように。
##ダウンロード
githubに置いてあります。