2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

画面遷移時に画像を渡す方法

Last updated at Posted at 2021-09-04

ソースが長くなってしまうので、画面遷移時に画像を渡す方法だけ記載しています。

画像の表示方法やフォトライブラリから画像を選ぶといった工程は全て省いています。
 
それを踏まえた上で書いていきます。

 
ソースコードは、遷移前と遷移後の二つのクラスがあります。
ViewController1は遷移前、ViewController2は遷移後のクラスとなってます。
 
まず遷移前のクラス(ViewController1)はこちら。

class ViewController1: UIViewController {

    @IBOutlet weak var imageView1: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let nextVC = storyboard.instantiateViewController(withIdentifier: "ViewController2") as! ViewController

        //ViewController1のimage(画像データ)をViewController2のimage(変数)に渡す
        nextVC.image = imageView1.image!
        
        //画面遷移
        present(nextVC, animated: true, completion: nil)
    }
}

 

CustomClassとIdentityは、ViewController2となっている想定です。
スクリーンショット 2021-09-05 7.37.43.png

クラス名はViewController2
storyboard名はMainとしています(必要に応じて変更してください。)
スクリーンショット 2021-09-05 7.40.47.png

そして遷移先(ViewController2)のクラスはこちら。

class ViewController2: UIViewController {

        @IBOutlet weak var imageView2: UIImageView!

        var image: UIImage?

        override func viewDidLoad() {
            super.viewDidLoad()

            //遷移元から取得したimage(画像データ)をimageView2のimageに渡す
            imageView2.image = image

        }
}

もしimageViewの大きさの分だけ大きくしたいという方はこちらを加えてください。

    // ↓自分で付けたUIImageViewの名前に変更
    imageView2.modalPresentationStyle = .fullScreen // ★この行追加

 
今回やっていることは二つだけです。

 
1.まずViewController1のimageView1のimageを遷移先(ViewController2)の変数(image)に渡します

    nextVC.image = imageView1.image!

 

2.そしてViewController2のimageView2のimageに変数(image)の値を渡します

        imageView2.image = image

 
ViewController2のimageという変数を使って、二つのViewControllerの橋渡しをしています。
 

ViewControler1のimageView1.image → image → ViewControler2のimageView2.image
 
 
Outlet接続のやり方がわからないという方はこちらを参考にどうぞ。

 

imageViewにボタンアクションをつけたいという方はこちらをどうぞ。

  
 
フォトライブラリから画像を選ぶ方法を知りたいという方はこちらを参考にどうぞ。

 
画像を表示させたいだけの方はこちらをどうぞ。

 
余談

imageという変数はもしかしたら必要ないかもしれません

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?