LoginSignup
20
26

More than 5 years have passed since last update.

Storyboardで作成したViewとコードで作成したViewの背面関係について

Last updated at Posted at 2015-05-29

問題

【理想】
storyboardで作成したButtonをコードで作成した背景の上に表示させたい。

【問題】
Buttonが表示されず背景のみ表示されている。
(背景の下にButtonが隠れてしまっている)

ぱっと、思いついた解決案→作成する順番を変えよう!(先にコードで背景を作成してからstoryboardでButtonを作成)

失敗・・・

【解決策】
self.view.bringSubviewToFront(View)→ 最前面にViewを表示する。
self.view.sendSubviewToBack(View)→最背面にViewを表示する。

これを使って【理想】どおりの実装を行ってみました。

実装

  1. アシスタントエディターで、プログラムへつなぎます。 スクリーンショット 2015-05-30 2.08.35.png

2.Viewの背面関係を設定する

今回は、背景の上にButtonを表示させたいので、
self.view.bringSubviewToFront(btn)
self.view.sendSubviewToBack(ImageView)となる。

ViewController.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var btn: UIButton!
    var image: UIImage = UIImage(named: "sample.jpeg")!
    var ImageView: UIImageView = UIImageView(frame: CGRectMake(0,0,750,1334))

    override func viewDidLoad() {
        super.viewDidLoad()

        ImageView.image = image
        ImageView.layer.position = CGPoint(x: self.view.bounds.width / 2,y: self.view.bounds.height / 2)

        self.view.addSubview(ImageView)

        self.view.bringSubviewToFront(btn)
        self.view.sendSubviewToBack(ImageView)





    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

3.走らせてみた結果
スクリーンショット 2015-05-30 2.16.14.png

まとめ

今回は、主にStoryboardで作成したView、コードで作成したViewの背面関係について書いてみましたが、Storyboardで作成したView同士の背面関係、コードで生成したView同士の背面関係も
self.view.bringSubviewToFront()
self.view.sendSubviewToBack()
で実装可能なので、ぜひ試してみてください。

20
26
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
20
26