
今回から何回かに分けてメニュー画面用のテーブルビューを実装したいと思います!
今回はとりあえず下記の感じまでやってみました!
動作環境は下記の通りです!
Xcode Version 12.5 Swift version 5.4
まずはサクッとナビゲーションコントローラーまわりの設定をしちゃいましょう!
前回作ったMenuViewController.swiftのviewDidLoad()内に下記コードを追加します!
ちなみに背景色のコードは削除してOKです!
//ナビゲーションコントローラーまわり
//タイトル
self.title = "メニュー"
//背景色
self.navigationController?.navigationBar.barTintColor = UIColor(hex: self.common.main , alpha: 1)
//セーフエリアとの境目の線を消す
self.navigationController?.navigationBar.shadowImage = UIImage()
//フォントの設定
self.navigationController?.navigationBar.titleTextAttributes
= [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont(name: "HiraMaruProN-W4", size: 20)!]
//Cancelボタンを追加
cancelBtn = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(self.cancelBtnTapped))
cancelBtn.tintColor = UIColor(hex: self.common.white , alpha: 1)
self.navigationItem.leftBarButtonItem = cancelBtn
ナビゲーションコントローラーのフォントや背景色の設定と、Cancelボタンも付けておきました!
Cancelボタンを押した時のコードは下記です!
下記コードをviewDidLoad()外に書いて下さい!
//Cancelボタン
var cancelBtn: UIBarButtonItem!
//Cancelボタンのメソッド
@objc func cancelBtnTapped() {
//前の画面に戻る
dismiss(animated: true, completion: nil)
}
これでビルドすると下記画像のようになってると思います!
Cancelボタンを押したらちゃんと前の画面に戻りますか??
ではテーブルビューをコードだけで実装したいと思います!
最終的にはセルの左側にアイコンを付けたいのですが、今回はとりあえず表示するところまで実装しました!
まずはテーブルビューの変数とセルに表示する配列を作ります!
下記コードをviewDidLoad()外に書いて下さい!
//テーブルビューの変数
var tableView: UITableView?
//セル用の配列
let items = ["貯金忘れ防止アラーム", "使い方", "シェア", "評価", "データリセット"]
次にデーブルビューの設定です!
下記コードをviewDidLoad()内に書いて下さい!
//テーブルビューの設定
self.tableView = {
let tableView = UITableView(frame: self.view.bounds, style: .plain)
tableView.autoresizingMask = [
.flexibleWidth,
.flexibleHeight
]
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
return tableView
}()
次にセルの設定をしていきます。
セルの数とかセルをタップした時のメソッドとかです!
下記コードをviewDidLoad()外に書いて下さい!
//テーブルビューまわり
//テーブルビューのセクションの数を設定
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//テーブルビューのセルの数を設定
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//配列itemsの数になるように設定
return self.items.count
}
//セルの設定
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
?? UITableViewCell(style: .default, reuseIdentifier: "Cell")
//セルに表示するテキストを設定
cell.textLabel?.text = self.items[indexPath.row]
//セルの右側に<を付ける
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
//セル選択時に背景色を変更しない
cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
}
//セルを選択した時の設定
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Selected! \(self.items[indexPath.row])")
}
コード内のコメントに書いてる通りですが一点だけ!
18行目です!
表示させるセルのテキストに何を表示させるか決めているコードです。
配列itemsに格納されている文字列を0から順番に表示させています。
実はこのメソッド内はfor文みたいに回っていて「indexPath.row」には0から順番にセルの数だけ数字が入っています。
なので、配列itemsの[]の中に「indexPath.row」を入れれば0から順番に配列の文字列を取り出せると言う仕組みになってます!
最後に下記を修正すれば完成です!
class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
これでビルドすれば冒頭の画像のようになってると思います!
あと、セルをタップしたらタップされたセルのテキストが出力されると思うのでそちらも確認してみて下さい!
今回はとりあえずテーブルビューを表示されるところまでやりました!
あとは細かいレイアウトの設定とアイコンの表示です!
これをするにはカスタムセルと言うやつで実装しないといけないので次回はその実装をします!
ここまで読んでくれた人ありがとうございました!
誰かの役に立ってると嬉しいな。
import UIKit
class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
//Commonクラスのインスタンス生成
let common = Common()
//Cancelボタン
var cancelBtn: UIBarButtonItem!
//テーブルビューの変数
var tableView: UITableView?
//セル用の配列
let items = ["貯金忘れ防止アラーム", "使い方", "シェア", "評価", "データリセット"]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(hex: self.common.sub , alpha: 1)
//ナビゲーションコントローラーまわり
//タイトル
self.title = "メニュー"
//背景色
self.navigationController?.navigationBar.barTintColor = UIColor(hex: self.common.main , alpha: 1)
//セーフエリアとの境目の線を消す
self.navigationController?.navigationBar.shadowImage = UIImage()
//フォントの設定
self.navigationController?.navigationBar.titleTextAttributes
= [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.font: UIFont(name: "HiraMaruProN-W4", size: 20)!]
//Cancelボタンを追加
cancelBtn = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(self.cancelBtnTapped))
cancelBtn.tintColor = UIColor(hex: self.common.white , alpha: 1)
self.navigationItem.leftBarButtonItem = cancelBtn
//テーブルビューの設定
self.tableView = {
let tableView = UITableView(frame: self.view.bounds, style: .plain)
tableView.autoresizingMask = [
.flexibleWidth,
.flexibleHeight
]
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
return tableView
}()
}
//Cancelボタンのメソッド
@objc func cancelBtnTapped() {
//前の画面に戻る
dismiss(animated: true, completion: nil)
}
//テーブルビューまわり
//テーブルビューのセクションの数を設定
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
//テーブルビューのセルの数を設定
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//配列itemsの数になるように設定
return self.items.count
}
//セルの設定
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
?? UITableViewCell(style: .default, reuseIdentifier: "Cell")
print(indexPath.row)
//セルに表示するテキストを設定
cell.textLabel?.text = self.items[indexPath.row]
//セルの右側に<を付ける
cell.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator
//セル選択時に背景色を変更しない
cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
}
//セルを選択した時の設定
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Selected! \(self.items[indexPath.row])")
}
}
コメントを残す