UITableView(テーブルビュー)
【テーブルビューをコードで作る】
Storyboardを使わずに、コードでテーブルビュー を作成します。 import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { //セクションに表示する let Sections: NSArray = ["セクション1","セクション2"] //セルに格納する let TODO1: NSArray = ["やること1","やること2"] //セルに格納する let TODO2: NSArray = ["やらないこと1","やらないこと2"] override func viewDidLoad() { super.viewDidLoad() let tableView: UITableView = UITableView(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH)) //テーブルビューセル名を登録する tableView.register(UITableViewCell.self, forCellReuseIdentifier: "todoCell") //delegateの設定 tableView.delegate = self //dataSourceの設定 tableView.dataSource = self //画面にテーブルビューを追加 self.view.addSubview(tableView) } //Section数を決める func numberOfSections(in tableView: UITableView) -> Int { return Sections.count } //Sectionの高さを決める func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 60 } //Sectionのタイトルを決める func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return Sections[section] as? String } //Sectionの背景とテキストの色を変更する func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { //背景色を変更する view.tintColor = UIColor(red: CGFloat(redColor), green: CGFloat(greenColor), blue: CGFloat(blueColor), alpha: 1.0) //テキスト色を変更する let header = view as! UITableViewHeaderFooterView header.textLabel?.textColor = .white header.layer.masksToBounds = true header.layer.borderColor = UIColor.gray.cgColor header.layer.borderWidth = 0.2 } //セルの高さを返すメソッド func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } //セルの数を設定する func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return TODO1.count case 1: return TODO2.count default: return 0 } } //セルに値を設定する func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let todocell = UITableViewCell(style: .subtitle, reuseIdentifier: "todocell") switch indexPath.section { case 0: todocell.textLabel!.text = ToDohome[indexPath.row] case 1: todocell.textLabel!.text = ToDoplay[indexPath.row] default: return todocell } return todocell } //セルがタップされた時の処理 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.section { case 0: print("セクション1_セルタップ") case 1: print("セクション2_セルタップ") default: return } } } |