はじめに
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()メソッドはデフォルトで最前面に出力する事が出来るからです。
ちょっとした事ですが、知っているのといないのとでは結果が全然変わります。
と、自分に言い聞かせながらコードを書いていこうと思います。