0
0

More than 1 year has passed since last update.

UIButtonを画面の最前面に出す!!

Last updated at Posted at 2022-02-05

はじめに

UIButtonを配置したものの、画面の背面に設置されてしまい、どうやったら前面に出すのか迷ってしまったので、解決方法を記述しておきます。


結論から

view.bringSubviewToFront(UIButtonの名前)

を実行すれば、UIButtonが前面に出てくれます。

以下に具体例を載せておきます。

TableViewを配置

コードでUITableViewを記述しています。

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let item = ["cell 1","cell 2","cell 3","cell 4","cell 5","cell 6","cell 7","cell 8","cell 9","cell 10",]

    override func viewDidLoad() {

    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView(frame: self.view.bounds, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self

        view.addSubview(tableView)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return item.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = item[indexPath.row]
        return cell
    }
}

UIButoonの配置

import UIKit


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    let item = ["cell 1","cell 2","cell 3","cell 4","cell 5","cell 6","cell 7","cell 8","cell 9","cell 10",]

    override func viewDidLoad() {
        super.viewDidLoad()
        let button = UIButton(type: UIButton.ButtonType.system)
        button.setTitle("Button", for: UIControl.State.normal)
        button.sizeToFit()
        button.center = self.view.center
        let tableView = UITableView(frame: self.view.bounds, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self

        view.addSubview(button)
        view.addSubview(tableView)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return item.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = item[indexPath.row]
        return cell
    }
}

このままでは、UIButtonが背面に設置されたままなので、最初に紹介した

view.bringSubviewToFront(button)

view.addSubview(tableView)

の下に記載すればOKです!!

さいごに

view.addSubview(button)
view.addSubview(tableView)
の順番を逆にする事でもUIBUttonを前面に出す事が出来ます。

addSubview()メソッドはデフォルトで最前面に出力する事が出来るからです。

ちょっとした事ですが、知っているのといないのとでは結果が全然変わります。
と、自分に言い聞かせながらコードを書いていこうと思います。

0
0
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
0
0