Skip to content

Instantly share code, notes, and snippets.

@takoikatakotako
Last active November 19, 2016 09:19
Show Gist options
  • Save takoikatakotako/03d842a3c371bdf7030ec6a7d0537e47 to your computer and use it in GitHub Desktop.
Save takoikatakotako/03d842a3c371bdf7030ec6a7d0537e47 to your computer and use it in GitHub Desktop.
最低限のUITableView
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
//テーブルビューインスタンス
private var myTableView: UITableView!
//テーブルビューに表示する配列
private var myItems: NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
//テーブルビューに表示する配列
myItems = ["りんご", "すいか", "もも", "さくらんぼ", "ぶどう", "なし"]
//Viewの大きさを取得
let viewWidth = self.view.frame.size.width
let viewHeight = self.view.frame.size.height
//テーブルビューの初期化
myTableView = UITableView()
//デリゲートの設定
myTableView.delegate = self
myTableView.dataSource = self
//テーブルビューの大きさの指定
myTableView.frame = CGRect(x: 0, y: 0, width: viewWidth, height: viewHeight)
//テーブルビューの設置
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(myTableView)
}
//MARK: テーブルビューのセルの数を設定する
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//テーブルビューのセルの数はmyItems配列の数とした
return self.myItems.count
}
//MARK: テーブルビューのセルの中身を設定する
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//myItems配列の中身をテキストにして登録した
let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")! as UITableViewCell
cell.textLabel?.text = self.myItems[indexPath.row] as? String
return cell
}
//Mark: テーブルビューのセルが押されたら呼ばれる
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("\(indexPath.row)番のセルを選択しました! ")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment