<Swift5>コードのみでTableViewを設置する!(コピペで使えます!)<Xcode11>
スポンサードリンク
スポンサードリンク
今回は、タイトル通りStoryBoardを使わずに、コードのみで、テーブルビューを設置する方法、そしてカスタマイズする方法を記述していきます。
StoryBoardも便利なのですが、やっぱり保守性等考えると、勝手が悪いので、本気の方は、storyboardは使わずに、コードでアプリ作りをしてみて下さい!
現時点(2019)で最新版です!(Swift関連古い記事多すぎですw)
コピー&ペーストで使えますので、そのままXcodeへコピペして、いろいろいじってみて下さい!!
その他のについては、記事内検索をご活用ください。
また掲載の無いものについては、コメント等に記載いただければ、数日中に掲載いたします。
import UIKit
//UITableViewDelegate,UITableViewDataSourceをクラスに追加
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{
//スクリーンの横幅、縦幅を定義
let screenWidth = Int(UIScreen.main.bounds.size.width)
let screenHeight = Int(UIScreen.main.bounds.size.height)
//テーブルビューインスタンス作成
var sampleTableView: UITableView = UITableView()
//テーブルに表示するセル配列
var exampleArray: [String] = ["0番上のセル", "1番目のセル", "2番目のセル"]
override func viewDidLoad() {
super.viewDidLoad()
//テーブルビューの設置場所を指定
sampleTableView.frame = CGRect(x:screenWidth * 0/100, y:screenHeight * 10/100,
width:screenWidth * 100/100, height:screenHeight * 80/100)
// sampleTableView の dataSource 問い合わせ先を self に
sampleTableView.delegate = self
// sampleTableView の delegate 問い合わせ先を self に
sampleTableView.dataSource = self
//cellに名前を付ける
sampleTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
//実際にviewにsampleTableViewを表示させる
self.view.addSubview(sampleTableView)
//cellの高さを指定
self.sampleTableView.rowHeight = 100
//セパレーターの色を指定
sampleTableView.separatorColor = UIColor.blue
//cellとcellの間にセパレーターをなくす
//sampleTableView.separatorStyle = UITableViewCell.SeparatorStyle.none
}
//セクション数を指定
func numberOfSections(in sampleTableView: UITableView) -> Int {
return 1
}
//表示するcellの数を指定
func tableView(_ sampleTableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//
return exampleArray.count
}
//cellのコンテンツ
func tableView(_ sampleTableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
//cellにはsampleArrayが一つずつ入るようにするよ!
cell.textLabel?.text = exampleArray[indexPath.row]
return cell
}
//cellが選択された時の処理
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("\(indexPath.row)番セルが押されたよ!")
}
//削除機能をち追加してみましょう!
func tableView(_ sampleTableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let deleteButton: UITableViewRowAction = UITableViewRowAction(style: .normal, title: "削除") { (action, index) -> Void in
self.exampleArray.remove(at: indexPath.row)
sampleTableView.deleteRows(at: [indexPath], with: .fade)
}
deleteButton.backgroundColor = UIColor.red
return [deleteButton]
}
}
他にもいろいろと手を加えられるので、したいことがあれば検索してみて下さい!!