Skip to content

Instantly share code, notes, and snippets.

@donguri9
Last active February 18, 2017 01:46
Show Gist options
  • Save donguri9/a019b566cfd2c5e77550062a8ac26eaa to your computer and use it in GitHub Desktop.
Save donguri9/a019b566cfd2c5e77550062a8ac26eaa to your computer and use it in GitHub Desktop.
Extensionを使ったTableView
import UIKit
class ViewController: UIViewController {
let fruits = ["リンゴ", "みかん", "ぶどう"]
var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// TableViewの生成(Status barの高さをずらして表示).
// Status Barの高さを取得する.
let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
// Viewの高さと幅を取得する.
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight))
myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
myTableView.dataSource = self
myTableView.delegate = self
self.view.addSubview(myTableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
/// TableViewのデリゲートメソッド・データソースメソッド
extension ViewController: UITableViewDelegate, UITableViewDataSource {
/// セルの個数を指定するデリゲートメソッド(必須)
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return fruits.count
}
/// セルに値を設定するデータソースメソッド(必須)
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// セルを取得する
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
// セルに表示する値を設定する
cell.textLabel!.text = fruits[indexPath.row]
return cell
}
/// セルが選択された時に呼ばれるデリゲートメソッド
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("セル番号:\(indexPath.row) セルの内容:\(fruits[indexPath.row])")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment